Python collections.ChainMap() Examples

The following are 30 code examples of collections.ChainMap(). 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 , or try the search function .
Example #1
Source File: talentpool.py    From bot with MIT License 6 votes vote down vote up
def unwatch_command(self, ctx: Context, user: FetchedMember, *, reason: str) -> None:
        """
        Ends the active nomination of the specified user with the given reason.

        Providing a `reason` is required.
        """
        active_nomination = await self.bot.api_client.get(
            self.api_endpoint,
            params=ChainMap(
                self.api_default_params,
                {"user__id": str(user.id)}
            )
        )

        if not active_nomination:
            await ctx.send(":x: The specified user does not have an active nomination")
            return

        [nomination] = active_nomination
        await self.bot.api_client.patch(
            f"{self.api_endpoint}/{nomination['id']}",
            json={'end_reason': reason, 'active': False}
        )
        await ctx.send(f":white_check_mark: Messages sent by {user} will no longer be relayed")
        self._remove_user(user.id) 
Example #2
Source File: misc.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def count(start=0, step=1):
    """
    ``itertools.count`` in Py 2.6 doesn't accept a step
    parameter. This is an enhanced version of ``itertools.count``
    for Py2.6 equivalent to ``itertools.count`` in Python 2.7+.
    """
    while True:
        yield start
        start += step


########################################################################
###  ChainMap (helper for configparser and string.Template)
###  From the Py3.4 source code. See also:
###    https://github.com/kkxue/Py2ChainMap/blob/master/py2chainmap.py
######################################################################## 
Example #3
Source File: misc.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def count(start=0, step=1):
    """
    ``itertools.count`` in Py 2.6 doesn't accept a step
    parameter. This is an enhanced version of ``itertools.count``
    for Py2.6 equivalent to ``itertools.count`` in Python 2.7+.
    """
    while True:
        yield start
        start += step


########################################################################
###  ChainMap (helper for configparser and string.Template)
###  From the Py3.4 source code. See also:
###    https://github.com/kkxue/Py2ChainMap/blob/master/py2chainmap.py
######################################################################## 
Example #4
Source File: helpers.py    From bot with MIT License 6 votes vote down vote up
def __init__(self, **kwargs) -> None:
        default_kwargs = {
            'id': next(self.discord_id),
            'name': 'role',
            'position': 1,
            'colour': discord.Colour(0xdeadbf),
            'permissions': discord.Permissions(),
        }
        super().__init__(**collections.ChainMap(kwargs, default_kwargs))

        if isinstance(self.colour, int):
            self.colour = discord.Colour(self.colour)

        if isinstance(self.permissions, int):
            self.permissions = discord.Permissions(self.permissions)

        if 'mention' not in kwargs:
            self.mention = f'&{self.name}' 
Example #5
Source File: string.py    From jawfish with MIT License 6 votes vote down vote up
def substitute(self, *args, **kws):
        if len(args) > 1:
            raise TypeError('Too many positional arguments')
        if not args:
            mapping = kws
        elif kws:
            mapping = ChainMap(kws, args[0])
        else:
            mapping = args[0]
        # Helper function for .sub()
        def convert(mo):
            # Check the most common path first.
            named = mo.group('named') or mo.group('braced')
            if named is not None:
                val = mapping[named]
                # We use this idiom instead of str() because the latter will
                # fail if val is a Unicode containing non-ASCII characters.
                return '%s' % (val,)
            if mo.group('escaped') is not None:
                return self.delimiter
            if mo.group('invalid') is not None:
                self._invalid(mo)
            raise ValueError('Unrecognized named group in pattern',
                             self.pattern)
        return self.pattern.sub(convert, self.template) 
Example #6
Source File: misc.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def count(start=0, step=1):
    """
    ``itertools.count`` in Py 2.6 doesn't accept a step
    parameter. This is an enhanced version of ``itertools.count``
    for Py2.6 equivalent to ``itertools.count`` in Python 2.7+.
    """
    while True:
        yield start
        start += step


########################################################################
###  ChainMap (helper for configparser and string.Template)
###  From the Py3.4 source code. See also:
###    https://github.com/kkxue/Py2ChainMap/blob/master/py2chainmap.py
######################################################################## 
Example #7
Source File: configparser.py    From jawfish with MIT License 6 votes vote down vote up
def _unify_values(self, section, vars):
        """Create a sequence of lookups with 'vars' taking priority over
        the 'section' which takes priority over the DEFAULTSECT.

        """
        sectiondict = {}
        try:
            sectiondict = self._sections[section]
        except KeyError:
            if section != self.default_section:
                raise NoSectionError(section)
        # Update with the entry specific variables
        vardict = {}
        if vars:
            for key, value in vars.items():
                if value is not None:
                    value = str(value)
                vardict[self.optionxform(key)] = value
        return _ChainMap(vardict, sectiondict, self._defaults) 
Example #8
Source File: test_transcoding.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_chainmap_with_tuple(self):
        value = ChainMap(dict(a=(1, 1)))
        encoded = (
            '{"__class__":{'
            '"state":{"maps":[{"a":{"__tuple__":[1,1]}}]},'
            '"topic":"collections#ChainMap"}}'
        )
        self.assertTranscoding(value, encoded) 
Example #9
Source File: compat.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def copy(self):
            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
            return self.__class__(self.maps[0].copy(), *self.maps[1:]) 
Example #10
Source File: compat.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *maps):
            '''Initialize a ChainMap by setting *maps* to the given mappings.
            If no mappings are provided, a single empty dictionary is used.

            '''
            self.maps = list(maps) or [{}]          # always at least one map 
Example #11
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def copy(self):
            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
            return self.__class__(self.maps[0].copy(), *self.maps[1:]) 
Example #12
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def fromkeys(cls, iterable, *args):
            'Create a ChainMap with a single dict created from the iterable.'
            return cls(dict.fromkeys(iterable, *args)) 
Example #13
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def __init__(self, *maps):
            '''Initialize a ChainMap by setting *maps* to the given mappings.
            If no mappings are provided, a single empty dictionary is used.

            '''
            self.maps = list(maps) or [{}]          # always at least one map 
Example #14
Source File: render1.py    From python-in-practice with GNU General Public License v3.0 5 votes vote down vote up
def __subclasshook__(Class, Subclass):
            if Class is Renderer:
                attributes = collections.ChainMap(*(Superclass.__dict__
                        for Superclass in Subclass.__mro__))
                methods = ("header", "paragraph", "footer")
                if all(method in attributes for method in methods):
                    return True
            return NotImplemented 
Example #15
Source File: compat.py    From Python24 with MIT License 5 votes vote down vote up
def new_child(self):                        # like Django's Context.push()
            'New ChainMap with a new dict followed by all previous maps.'
            return self.__class__({}, *self.maps) 
Example #16
Source File: compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def parents(self):                          # like Django's Context.pop()
            'New ChainMap from maps[1:].'
            return self.__class__(*self.maps[1:]) 
Example #17
Source File: compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def new_child(self):                        # like Django's Context.push()
            'New ChainMap with a new dict followed by all previous maps.'
            return self.__class__({}, *self.maps) 
Example #18
Source File: compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def copy(self):
            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
            return self.__class__(self.maps[0].copy(), *self.maps[1:]) 
Example #19
Source File: compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def fromkeys(cls, iterable, *args):
            'Create a ChainMap with a single dict created from the iterable.'
            return cls(dict.fromkeys(iterable, *args)) 
Example #20
Source File: compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __init__(self, *maps):
            '''Initialize a ChainMap by setting *maps* to the given mappings.
            If no mappings are provided, a single empty dictionary is used.

            '''
            self.maps = list(maps) or [{}]          # always at least one map 
Example #21
Source File: helpers.py    From linter-pylama with MIT License 5 votes vote down vote up
def __init__(self, *maps):
        '''Initialize a ChainMap by setting *maps* to the given mappings.
        If no mappings are provided, a single empty dictionary is used.

        '''
        self.maps = list(maps) or [{}]          # always at least one map 
Example #22
Source File: helpers.py    From configparser with MIT License 5 votes vote down vote up
def parents(self):  # like Django's Context.pop()
        'New ChainMap from maps[1:].'
        return self.__class__(*self.maps[1:]) 
Example #23
Source File: helpers.py    From configparser with MIT License 5 votes vote down vote up
def new_child(self):  # like Django's Context.push()
        'New ChainMap with a new dict followed by all previous maps.'
        return self.__class__({}, *self.maps) 
Example #24
Source File: helpers.py    From configparser with MIT License 5 votes vote down vote up
def copy(self):
        """
        New ChainMap or subclass with a new copy of
        maps[0] and refs to maps[1:]
        """
        return self.__class__(self.maps[0].copy(), *self.maps[1:]) 
Example #25
Source File: helpers.py    From configparser with MIT License 5 votes vote down vote up
def fromkeys(cls, iterable, *args):
        'Create a ChainMap with a single dict created from the iterable.'
        return cls(dict.fromkeys(iterable, *args)) 
Example #26
Source File: helpers.py    From configparser with MIT License 5 votes vote down vote up
def __init__(self, *maps):
        '''Initialize a ChainMap by setting *maps* to the given mappings.
        If no mappings are provided, a single empty dictionary is used.

        '''
        self.maps = list(maps) or [{}]  # always at least one map 
Example #27
Source File: helpers.py    From linter-pylama with MIT License 5 votes vote down vote up
def parents(self):                          # like Django's Context.pop()
        'New ChainMap from maps[1:].'
        return self.__class__(*self.maps[1:]) 
Example #28
Source File: helpers.py    From linter-pylama with MIT License 5 votes vote down vote up
def new_child(self):                        # like Django's Context.push()
        'New ChainMap with a new dict followed by all previous maps.'
        return self.__class__({}, *self.maps) 
Example #29
Source File: helpers.py    From linter-pylama with MIT License 5 votes vote down vote up
def copy(self):
        'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
        return self.__class__(self.maps[0].copy(), *self.maps[1:]) 
Example #30
Source File: helpers.py    From linter-pylama with MIT License 5 votes vote down vote up
def fromkeys(cls, iterable, *args):
        'Create a ChainMap with a single dict created from the iterable.'
        return cls(dict.fromkeys(iterable, *args))