Python collections.abc.MutableSequence() Examples

The following are 27 code examples of collections.abc.MutableSequence(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections.abc , or try the search function .
Example #1
Source File: _config.py    From messages with MIT License 6 votes vote down vote up
def update_config_pwd(msg, cfg):
    """
    Updates the profile's auth entry with values set by the user.
    This will overwrite existing values.

    Args:
        :msg: (Message class) an instance of a message class.
        :cfg: (jsonconfig.Config) config instance.
    """
    msg_type = msg.__class__.__name__.lower()
    key_fmt = msg.profile + "_" + msg_type
    if isinstance(msg._auth, (MutableSequence, tuple)):
        cfg.pwd[key_fmt] = " :: ".join(msg._auth)
    else:
        cfg.pwd[key_fmt] = msg._auth


##############################################################################
#  Config functions used by the CLI to create profile entries
############################################################################## 
Example #2
Source File: replacer.py    From punch with ISC License 6 votes vote down vote up
def update(self, serializers):
        # Serializers is a list
        if isinstance(serializers, abc.MutableSequence):
            self.serializers = dict(
                ((str(k), v) for k, v in enumerate(serializers))
            )
        # Serializers is a string
        elif isinstance(serializers, abc.Sequence):
            self.serializers = {
                '0': serializers
            }
        # Serializers is a dictionary
        elif isinstance(serializers, abc.Mapping):
            self.serializers.update(serializers)
        else:
            raise(TypeError(
                ("serializers must be either a MutableSequence, "
                 "a Sequence, or a Mapping.")
            )) 
Example #3
Source File: _utils.py    From messages with MIT License 5 votes vote down vote up
def check_valid(msg_type, attr, value, func, exec_info):
    """
    Checker function all validate_* functions below will call.
    Raises InvalidMessageInputError if input is not valid as per
    given func.
    """
    if value is not None:
        if isinstance(value, MutableSequence):
            for v in value:
                if not func(v):
                    raise InvalidMessageInputError(msg_type, attr, value, exec_info)
        else:
            if not func(value):
                raise InvalidMessageInputError(msg_type, attr, value, exec_info) 
Example #4
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
def test_MutableSequence(self):
        for sample in [tuple, str, bytes]:
            self.assertNotIsInstance(sample(), MutableSequence)
            self.assertFalse(issubclass(sample, MutableSequence))
        for sample in [list, bytearray, deque]:
            self.assertIsInstance(sample(), MutableSequence)
            self.assertTrue(issubclass(sample, MutableSequence))
        self.assertFalse(issubclass(str, MutableSequence))
        self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
            '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') 
Example #5
Source File: explore1.py    From example-code with MIT License 5 votes vote down vote up
def build(cls, obj):
        if isinstance(obj, abc.Mapping):
            return cls(obj)
        elif isinstance(obj, abc.MutableSequence):
            return [cls.build(item) for item in obj]
        else:  # <8>
            return obj 
Example #6
Source File: explore0.py    From example-code with MIT License 5 votes vote down vote up
def build(cls, obj):  # <5>
        if isinstance(obj, abc.Mapping):  # <6>
            return cls(obj)
        elif isinstance(obj, abc.MutableSequence):  # <7>
            return [cls.build(item) for item in obj]
        else:  # <8>
            return obj
# END EXPLORE0 
Example #7
Source File: explore2.py    From example-code with MIT License 5 votes vote down vote up
def __new__(cls, arg):  # <1>
        if isinstance(arg, abc.Mapping):
            return super().__new__(cls)  # <2>
        elif isinstance(arg, abc.MutableSequence):  # <3>
            return [cls(item) for item in arg]
        else:
            return arg 
Example #8
Source File: core.py    From forte with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, index: Union[int, slice]
                    ) -> Union[EntryType, MutableSequence]:
        if isinstance(index, slice):
            return [self.__parent_entry.resolve_pointer(d) for d in
                    self.__data[index]]
        else:
            return self.__parent_entry.resolve_pointer(self.__data[index]) 
Example #9
Source File: core.py    From forte with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, s: slice) -> MutableSequence:
        ... 
Example #10
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_MutableSequence(self):
        for sample in [tuple, str, bytes]:
            self.assertNotIsInstance(sample(), MutableSequence)
            self.assertFalse(issubclass(sample, MutableSequence))
        for sample in [list, bytearray, deque]:
            self.assertIsInstance(sample(), MutableSequence)
            self.assertTrue(issubclass(sample, MutableSequence))
        self.assertFalse(issubclass(str, MutableSequence))
        self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
            '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') 
Example #11
Source File: util.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hashable(x):
    if isinstance(x, MutableSequence):
        return tuple(x)
    elif isinstance(x, MutableMapping):
        return tuple([(k,v) for k,v in x.items()])
    else:
        return x 
Example #12
Source File: explore1.py    From notebooks with MIT License 5 votes vote down vote up
def build(cls, obj):
        if isinstance(obj, abc.Mapping):
            return cls(obj)
        elif isinstance(obj, abc.MutableSequence):
            return [cls.build(item) for item in obj]
        else:  # <8>
            return obj 
Example #13
Source File: explore0.py    From notebooks with MIT License 5 votes vote down vote up
def build(cls, obj):  # <5>
        if isinstance(obj, abc.Mapping):  # <6>
            return cls(obj)
        elif isinstance(obj, abc.MutableSequence):  # <7>
            return [cls.build(item) for item in obj]
        else:  # <8>
            return obj
# END EXPLORE0 
Example #14
Source File: explore2.py    From notebooks with MIT License 5 votes vote down vote up
def __new__(cls, arg):  # <1>
        if isinstance(arg, abc.Mapping):
            return super().__new__(cls)  # <2>
        elif isinstance(arg, abc.MutableSequence):  # <3>
            return [cls(item) for item in arg]
        else:
            return arg 
Example #15
Source File: test_collections.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_MutableSequence(self):
        for sample in [tuple, str, bytes]:
            self.assertNotIsInstance(sample(), MutableSequence)
            self.assertFalse(issubclass(sample, MutableSequence))
        for sample in [list, bytearray]:
            self.assertIsInstance(sample(), MutableSequence)
            self.assertTrue(issubclass(sample, MutableSequence))
        self.assertFalse(issubclass(str, MutableSequence))
        self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
            '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') 
Example #16
Source File: test_array.py    From chaquopy with MIT License 5 votes vote down vote up
def test_abc(self):
        from collections import abc
        for element_type_1d in [jboolean, jbyte, jshort, jint, jlong, jfloat, jdouble, jchar,
                                String]:
            for element_type in [element_type_1d, jarray(element_type_1d)]:
                with self.subTest(element_type=element_type):
                    cls = jarray(element_type)
                    self.assertTrue(issubclass(cls, abc.MutableSequence))
                    self.assertTrue(isinstance(cls([]), abc.MutableSequence)) 
Example #17
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_MutableSequence(self):
        for sample in [tuple, str, bytes]:
            self.assertNotIsInstance(sample(), MutableSequence)
            self.assertFalse(issubclass(sample, MutableSequence))
        for sample in [list, bytearray, deque]:
            self.assertIsInstance(sample(), MutableSequence)
            self.assertTrue(issubclass(sample, MutableSequence))
        self.assertFalse(issubclass(str, MutableSequence))
        self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
            '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') 
Example #18
Source File: schemas.py    From testplan with Apache License 2.0 5 votes vote down vote up
def _deserialize(self, value, attr, obj, recurse_lvl=0):
        """
        Check deeply to see if there is a {'bytes': [...]} dict and if so
        convert it to a bytes object
        """
        if recurse_lvl == 0:
            valued = super(EntriesField, self)._deserialize(value, attr, obj)
        else:
            valued = value
        if isinstance(valued, MutableMapping):
            for key in six.iterkeys(valued):
                if key == self._BYTES_KEY:
                    return self._hex_list_to_binary(valued[key])
                valued[key] = self._deserialize(
                    value=valued[key],
                    attr=attr,
                    obj=obj,
                    recurse_lvl=(recurse_lvl + 1),
                )
            return valued
        if isinstance(valued, MutableSequence):
            for i in range(len(valued)):
                valued[i] = self._deserialize(
                    value=valued[i],
                    attr=attr,
                    obj=obj,
                    recurse_lvl=(recurse_lvl + 1),
                )
            return valued
        return valued 
Example #19
Source File: email_.py    From messages with MIT License 5 votes vote down vote up
def list_to_string(recipient):
        """
        Format the recipient for the MIMEMultipart() email type.
        If the recipient is a list, then it returns the list as a
        comma separated string.
        example: input=['you@here.com', 'her@there.com']
                 output='you@there.com, her@there.com'
        """
        if recipient:
            if isinstance(recipient, MutableSequence):
                return ", ".join(recipient)
            return recipient 
Example #20
Source File: blueprint_group.py    From sanic with MIT License 5 votes vote down vote up
def insert(self, index: int, item: object) -> None:
        """
        The Abstract class `MutableSequence` leverages this insert method to
        perform the `BlueprintGroup.append` operation.

        :param index: Index to use for removing a new Blueprint item
        :param item: New `Blueprint` object.
        :return: None
        """
        self._blueprints.insert(index, item) 
Example #21
Source File: test_collections.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_MutableSequence_mixins(self):
        # Test the mixins of MutableSequence by creating a miminal concrete
        # class inherited from it.
        class MutableSequenceSubclass(MutableSequence):
            def __init__(self):
                self.lst = []

            def __setitem__(self, index, value):
                self.lst[index] = value

            def __getitem__(self, index):
                return self.lst[index]

            def __len__(self):
                return len(self.lst)

            def __delitem__(self, index):
                del self.lst[index]

            def insert(self, index, value):
                self.lst.insert(index, value)

        mss = MutableSequenceSubclass()
        mss.append(0)
        mss.extend((1, 2, 3, 4))
        self.assertEqual(len(mss), 5)
        self.assertEqual(mss[3], 3)
        mss.reverse()
        self.assertEqual(mss[3], 1)
        mss.pop()
        self.assertEqual(len(mss), 4)
        mss.remove(3)
        self.assertEqual(len(mss), 3)
        mss += (10, 20, 30)
        self.assertEqual(len(mss), 6)
        self.assertEqual(mss[-1], 30)
        mss.clear()
        self.assertEqual(len(mss), 0)

################################################################################
### Counter
################################################################################ 
Example #22
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def test_MutableSequence_mixins(self):
        # Test the mixins of MutableSequence by creating a miminal concrete
        # class inherited from it.
        class MutableSequenceSubclass(MutableSequence):
            def __init__(self):
                self.lst = []

            def __setitem__(self, index, value):
                self.lst[index] = value

            def __getitem__(self, index):
                return self.lst[index]

            def __len__(self):
                return len(self.lst)

            def __delitem__(self, index):
                del self.lst[index]

            def insert(self, index, value):
                self.lst.insert(index, value)

        mss = MutableSequenceSubclass()
        mss.append(0)
        mss.extend((1, 2, 3, 4))
        self.assertEqual(len(mss), 5)
        self.assertEqual(mss[3], 3)
        mss.reverse()
        self.assertEqual(mss[3], 1)
        mss.pop()
        self.assertEqual(len(mss), 4)
        mss.remove(3)
        self.assertEqual(len(mss), 3)
        mss += (10, 20, 30)
        self.assertEqual(len(mss), 6)
        self.assertEqual(mss[-1], 30)
        mss.clear()
        self.assertEqual(len(mss), 0)

################################################################################
### Counter
################################################################################ 
Example #23
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 4 votes vote down vote up
def test_MutableSequence_mixins(self):
        # Test the mixins of MutableSequence by creating a miminal concrete
        # class inherited from it.
        class MutableSequenceSubclass(MutableSequence):
            def __init__(self):
                self.lst = []

            def __setitem__(self, index, value):
                self.lst[index] = value

            def __getitem__(self, index):
                return self.lst[index]

            def __len__(self):
                return len(self.lst)

            def __delitem__(self, index):
                del self.lst[index]

            def insert(self, index, value):
                self.lst.insert(index, value)

        mss = MutableSequenceSubclass()
        mss.append(0)
        mss.extend((1, 2, 3, 4))
        self.assertEqual(len(mss), 5)
        self.assertEqual(mss[3], 3)
        mss.reverse()
        self.assertEqual(mss[3], 1)
        mss.pop()
        self.assertEqual(len(mss), 4)
        mss.remove(3)
        self.assertEqual(len(mss), 3)
        mss += (10, 20, 30)
        self.assertEqual(len(mss), 6)
        self.assertEqual(mss[-1], 30)
        mss.clear()
        self.assertEqual(len(mss), 0)

################################################################################
### Counter
################################################################################ 
Example #24
Source File: schemas.py    From testplan with Apache License 2.0 4 votes vote down vote up
def _render_unencodable_bytes_by_callable(
        self, data, binary_serializer, recurse_lvl=0
    ):
        """
        Find the lowest level at which encoding fails - if at all - and
        serialize the byte-representation of that with the
        ``binary_serializer`` function.

        :param data: Any data that's meant to be serialized
        :type data: Any
        :param binary_serializer: A callable that takes a binary object and
                                  returns its serialized representation
        :type binary_serializer: Callable[[bytes], Any]

        :returns: Serialized representation of ``data``
        :rtype: Any
        """
        if recurse_lvl == 0:
            datacp = deepcopy(data)
        else:
            datacp = data
        try:
            json.dumps(datacp, ensure_ascii=True)
            return datacp
        except (UnicodeDecodeError, TypeError):
            if isinstance(datacp, MutableMapping):
                for key in six.iterkeys(datacp):
                    datacp[key] = self._render_unencodable_bytes_by_callable(
                        data=datacp[key],
                        binary_serializer=binary_serializer,
                        recurse_lvl=(recurse_lvl + 1),
                    )
                return datacp
            if isinstance(datacp, MutableSequence):
                for i in range(len(datacp)):
                    datacp[i] = self._render_unencodable_bytes_by_callable(
                        data=datacp[i],
                        binary_serializer=binary_serializer,
                        recurse_lvl=(recurse_lvl + 1),
                    )
                return datacp
            return {self._BYTES_KEY: binary_serializer(datacp)} 
Example #25
Source File: core.py    From django-more with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def apply(self, attrs=None, kattrs=None, merge=False):
        """ Apply new attributes or classes to the target """
        for attr in attrs:
            kattrs = kattrs or {}
            # Treat objects as assigned to their name
            if hasattr(attr, "__name__"):
                kattrs[attr.__name__] = attr
            else:
                kattrs[attr] = inspect.getattr_static(self.source, attr)
        for attr, value in kattrs.items():
            old_value = inspect.getattr_static(self.target, attr, None)
            # If callable, preserve old func
            if callable(value) and callable(old_value):
                # Prevent duplicate patching
                if value in patchy_records:
                    continue
                patchy_records[value] = old_value

            # Merge collections and classes instead of replacing
            if merge:
                if isinstance(old_value, abc.Container):
                    if isinstance(value, abc.Mapping) and isinstance(old_value, abc.MutableMapping):
                        old_value.update(value)
                        logger.info('Merging mapping {mod}.{attr}'.format(mod=self.target.__name__, attr=attr))
                    elif isinstance(value, abc.Sequence) and isinstance(old_value, abc.MutableSequence):
                        old_value.extend(value)
                        logger.info('Merging sequence {mod}.{attr}'.format(mod=self.target.__name__, attr=attr))
                    elif isinstance(value, abc.Set) and isinstance(old_value, abc.MutableSet):
                        old_value.update(value)
                        logger.info('Merging set {mod}.{attr}'.format(mod=self.target.__name__, attr=attr))
                    else:
                        setattr(self.target, attr, value)
                        logger.info("Couldn't merge collection {target}.{attr}, replaced instead".format(
                            target=self.target.__name__,
                            attr=attr))
                    continue
                elif isinstance(old_value, type):
                    logger.info('Merging class for {target}.{attr}'.format(
                        target=self.target.__name__, attr=attr))
                    self.cls(old_value, value).auto()
                    continue
            logger.info('Setting value {target}.{attr}'.format(target=self.target.__name__, attr=attr))
            # Apply patched value
            setattr(self.target, attr, value) 
Example #26
Source File: email_.py    From messages with MIT License 4 votes vote down vote up
def send(self):
        """
        Send the message.
        First, a message is constructed, then a session with the email
        servers is created, finally the message is sent and the session
        is stopped.
        """
        self._generate_email()

        if self.verbose:
            print(
                "Debugging info"
                "\n--------------"
                "\n{} Message created.".format(timestamp())
            )

        recipients = []
        for i in (self.to, self.cc, self.bcc):
            if i:
                if isinstance(i, MutableSequence):
                    recipients += i
                else:
                    recipients.append(i)

        session = self._get_session()
        if self.verbose:
            print(timestamp(), "Login successful.")

        session.sendmail(self.from_, recipients, self.message.as_string())
        session.quit()

        if self.verbose:
            print(timestamp(), "Logged out.")

        if self.verbose:
            print(
                timestamp(),
                type(self).__name__ + " info:",
                self.__str__(indentation="\n * "),
            )

        print("Message sent.") 
Example #27
Source File: test_collections.py    From android_universal with MIT License 4 votes vote down vote up
def test_MutableSequence_mixins(self):
        # Test the mixins of MutableSequence by creating a minimal concrete
        # class inherited from it.
        class MutableSequenceSubclass(MutableSequence):
            def __init__(self):
                self.lst = []

            def __setitem__(self, index, value):
                self.lst[index] = value

            def __getitem__(self, index):
                return self.lst[index]

            def __len__(self):
                return len(self.lst)

            def __delitem__(self, index):
                del self.lst[index]

            def insert(self, index, value):
                self.lst.insert(index, value)

        mss = MutableSequenceSubclass()
        mss.append(0)
        mss.extend((1, 2, 3, 4))
        self.assertEqual(len(mss), 5)
        self.assertEqual(mss[3], 3)
        mss.reverse()
        self.assertEqual(mss[3], 1)
        mss.pop()
        self.assertEqual(len(mss), 4)
        mss.remove(3)
        self.assertEqual(len(mss), 3)
        mss += (10, 20, 30)
        self.assertEqual(len(mss), 6)
        self.assertEqual(mss[-1], 30)
        mss.clear()
        self.assertEqual(len(mss), 0)

################################################################################
### Counter
################################################################################