Python collections.ChainMap() Examples

The following are code examples for showing how to use collections.ChainMap(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: bot   Author: python-discord   File: talentpool.py    MIT License 7 votes vote down vote up
def unwatch_command(self, ctx: Context, user: Union[User, proxy_user], *, 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
Project: reportengine   Author: NNPDF   File: test_complexinput.py    GNU General Public License v2.0 6 votes vote down vote up
def produce_matched_datasets_from_dataspecs(self, dataspecs):
        all_names = []
        for spec in dataspecs:
            with self.set_context(ns=self._curr_ns.new_child(spec)):
                _, datasets = self.parse_from_(
                    None, 'datasets', write=False)
                names = {ds.split()[1]: ds for ds in datasets}
                all_names.append(names)
        used_set = set.intersection(*(set(d) for d in all_names))

        res = []
        for k in used_set:
            inres = {'dataset_name': k}
            inner_spec_list = inres['dataspecs'] = []
            for ispec, spec in enumerate(dataspecs):
                d = ChainMap({
                    'dataset': all_names[ispec][k],
                }, spec)
                inner_spec_list.append(d)
            res.append(inres)
        res.sort(key=lambda x: (x['dataset_name']))
        return res 
Example 3
Project: reportengine   Author: NNPDF   File: test_complexinput.py    GNU General Public License v2.0 6 votes vote down vote up
def test_nsexpand(self):
        spec = ('pdfsets', 'theories', 'datasets')
        c = Config(inp)
        ns = utils.ChainMap()
        specs = c.process_fuzzyspec(spec, ns=ns)
        self.assertEqual(len(specs), 8)
        datasets = [
              'ds: d1 (theory: th 1, cuts: False)',
              'ds: d2 (theory: th 1, cuts: False)',
              'ds: d1 (theory: th 2, cuts: False)',
              'ds: d2 (theory: th 2, cuts: False)',
              'ds: d1 (theory: th 1, cuts: False)',
              'ds: d2 (theory: th 1, cuts: False)',
              'ds: d1 (theory: th 2, cuts: False)',
              'ds: d2 (theory: th 2, cuts: False)']
        for spec, ds in zip(specs, datasets):
            self.assertEqual(namespaces.resolve(ns, spec)['dataset'], ds) 
Example 4
Project: pcc   Author: jiamo   File: util.py    The Unlicense 6 votes vote down vote up
def checked(func):
    sig = signature(func)   # can be bind here
    # ann = func.__annotations__
    ann = ChainMap(
        func.__annotations__,
        func.__globals__.get('__annotations__', {})
        # what the func :dx is __annotations__  in modu
    )
    print("ann is ", ann)
    @wraps(func)
    def wrapper(*args, **kwargs):
        bound = sig.bind(*args, **kwargs)
        for name, val in bound.arguments.items():
            if name in ann:
                print("check ", name)
                ann[name].check(val)
        return func(*args, **kwargs)
    return wrapper 
Example 5
Project: jawfish   Author: war-and-code   File: string.py    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
Project: jawfish   Author: war-and-code   File: configparser.py    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 7
Project: bot   Author: python-discord   File: bigbrother.py    MIT License 6 votes vote down vote up
def unwatch_command(self, ctx: Context, user: Union[User, proxy_user], *, reason: str) -> None:
        """Stop relaying messages by the given `user`."""
        active_watches = await self.bot.api_client.get(
            self.api_endpoint,
            params=ChainMap(
                self.api_default_params,
                {"user__id": str(user.id)}
            )
        )
        if active_watches:
            [infraction] = active_watches

            await self.bot.api_client.patch(
                f"{self.api_endpoint}/{infraction['id']}",
                json={'active': False}
            )

            await post_infraction(ctx, user, 'watch', f"Unwatched: {reason}", hidden=True, active=False)

            await ctx.send(f":white_check_mark: Messages sent by {user} will no longer be relayed.")

            self._remove_user(user.id)
        else:
            await ctx.send(":x: The specified user is currently not being watched.") 
Example 8
Project: NiujiaoDebugger   Author: MrSrc   File: configparser.py    GNU General Public License v3.0 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) from None
        # 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 9
Project: NiujiaoDebugger   Author: MrSrc   File: test_collections.py    GNU General Public License v3.0 6 votes vote down vote up
def test_missing(self):
        class DefaultChainMap(ChainMap):
            def __missing__(self, key):
                return 999
        d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30))
        for k, v in dict(a=1, b=2, c=30, d=999).items():
            self.assertEqual(d[k], v)                                  # check __getitem__ w/missing
        for k, v in dict(a=1, b=2, c=30, d=77).items():
            self.assertEqual(d.get(k, 77), v)                          # check get() w/ missing
        for k, v in dict(a=True, b=True, c=True, d=False).items():
            self.assertEqual(k in d, v)                                # check __contains__ w/missing
        self.assertEqual(d.pop('a', 1001), 1, d)
        self.assertEqual(d.pop('a', 1002), 1002)                       # check pop() w/missing
        self.assertEqual(d.popitem(), ('b', 2))                        # check popitem() w/missing
        with self.assertRaises(KeyError):
            d.popitem() 
Example 10
Project: NiujiaoDebugger   Author: MrSrc   File: test_collections.py    GNU General Public License v3.0 6 votes vote down vote up
def test_order_preservation(self):
        d = ChainMap(
                OrderedDict(j=0, h=88888),
                OrderedDict(),
                OrderedDict(i=9999, d=4444, c=3333),
                OrderedDict(f=666, b=222, g=777, c=333, h=888),
                OrderedDict(),
                OrderedDict(e=55, b=22),
                OrderedDict(a=1, b=2, c=3, d=4, e=5),
                OrderedDict(),
            )
        self.assertEqual(''.join(d), 'abcdefghij')
        self.assertEqual(list(d.items()),
            [('a', 1), ('b', 222), ('c', 3333), ('d', 4444),
             ('e', 55), ('f', 666), ('g', 777), ('h', 88888),
             ('i', 9999), ('j', 0)]) 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: test_typing.py    GNU General Public License v3.0 6 votes vote down vote up
def test_type_erasure_special(self):
        T = TypeVar('T')
        # this is the only test that checks type caching
        self.clear_caches()
        class MyTup(Tuple[T, T]): ...
        self.assertIs(MyTup[int]().__class__, MyTup)
        self.assertIs(MyTup[int]().__orig_class__, MyTup[int])
        class MyCall(Callable[..., T]):
            def __call__(self): return None
        self.assertIs(MyCall[T]().__class__, MyCall)
        self.assertIs(MyCall[T]().__orig_class__, MyCall[T])
        class MyDict(typing.Dict[T, T]): ...
        self.assertIs(MyDict[int]().__class__, MyDict)
        self.assertIs(MyDict[int]().__orig_class__, MyDict[int])
        class MyDef(typing.DefaultDict[str, T]): ...
        self.assertIs(MyDef[int]().__class__, MyDef)
        self.assertIs(MyDef[int]().__orig_class__, MyDef[int])
        # ChainMap was added in 3.3
        if sys.version_info >= (3, 3):
            class MyChain(typing.ChainMap[str, T]): ...
            self.assertIs(MyChain[int]().__class__, MyChain)
            self.assertIs(MyChain[int]().__orig_class__, MyChain[int]) 
Example 12
Project: IsThatWho   Author: justanr   File: tmdb.py    MIT License 5 votes vote down vote up
def intersect(self, ids):
        movies = self._tmdb.fetch_many(ids)
        return ChainMap(intersect_crews(movies), intersect_casts(movies)) 
Example 13
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    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
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    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 15
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    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 16
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    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 17
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    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 18
Project: L   Author: vaultah   File: posts.py    MIT License 5 votes vote down vote up
def derived(item, reflections=False):
    if not item.good():
        raise ValueError('The post does not exists')
    # Refillable list of replies of any type
    replies = [item]
    # Common selectors
    spec = ChainMap({})

    while replies:
        temp, bases = [], [[x.id, x.type] for x in replies]
        derivations = {(x.id, x.type): x.derived for x in replies}
        kw = {'filter': spec.new_child({'base': {'$in': bases}}),
              'cursor_type': CursorType.EXHAUST}
 
        # Applies to posts only
        if not reflections:
            kw['filter'] = kw['filter'].new_child({'$or': [
                {'content': {'$exists': True}},
                {'images': {'$exists': True}}
            ]})

        kw['filter'] = dict(kw['filter'])

        for document in Post.collection.find(**kw):
            v = Post.fromdata(document)
            derivations[tuple(v.base)].append(v)
            temp.append(v)

        yield replies

        replies = temp 
Example 19
Project: flasky   Author: RoseOu   File: compat.py    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 20
Project: flasky   Author: RoseOu   File: compat.py    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 21
Project: flasky   Author: RoseOu   File: compat.py    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 22
Project: flasky   Author: RoseOu   File: compat.py    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 23
Project: flasky   Author: RoseOu   File: compat.py    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 24
Project: sic   Author: Yanixos   File: compat.py    GNU General Public License v3.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 25
Project: sic   Author: Yanixos   File: compat.py    GNU General Public License v3.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 26
Project: sic   Author: Yanixos   File: compat.py    GNU General Public License v3.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 27
Project: sic   Author: Yanixos   File: compat.py    GNU General Public License v3.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 28
Project: sic   Author: Yanixos   File: compat.py    GNU General Public License v3.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 29
Project: AshsSDK   Author: thehappydinoa   File: compat.py    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 30
Project: AshsSDK   Author: thehappydinoa   File: compat.py    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 31
Project: AshsSDK   Author: thehappydinoa   File: compat.py    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 32
Project: AshsSDK   Author: thehappydinoa   File: compat.py    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 33
Project: AshsSDK   Author: thehappydinoa   File: compat.py    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 34
Project: pcc   Author: jiamo   File: util.py    The Unlicense 5 votes vote down vote up
def __prepare__(cls, *args):
        return ChainMap({}, _contracts) 
Example 35
Project: jawfish   Author: war-and-code   File: string.py    MIT License 5 votes vote down vote up
def safe_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):
            named = mo.group('named') or mo.group('braced')
            if named is not None:
                try:
                    # We use this idiom instead of str() because the latter
                    # will fail if val is a Unicode containing non-ASCII
                    return '%s' % (mapping[named],)
                except KeyError:
                    return mo.group()
            if mo.group('escaped') is not None:
                return self.delimiter
            if mo.group('invalid') is not None:
                return mo.group()
            raise ValueError('Unrecognized named group in pattern',
                             self.pattern)
        return self.pattern.sub(convert, self.template)



########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class

# The hard parts are reused from the C implementation.  They're exposed as "_"
# prefixed methods of str.

# The overall parser is implemented in _string.formatter_parser.
# The field name parser is implemented in _string.formatter_field_name_split 
Example 36
Project: Repobot   Author: Desgard   File: compat.py    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 37
Project: Repobot   Author: Desgard   File: compat.py    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 38
Project: Repobot   Author: Desgard   File: compat.py    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 39
Project: Repobot   Author: Desgard   File: compat.py    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 40
Project: Repobot   Author: Desgard   File: compat.py    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 41
Project: Repobot   Author: Desgard   File: misc.py    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 42
Project: Repobot   Author: Desgard   File: misc.py    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 43
Project: Repobot   Author: Desgard   File: misc.py    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 44
Project: Repobot   Author: Desgard   File: misc.py    MIT License 5 votes vote down vote up
def new_child(self, m=None):                # like Django's Context.push()
        '''
        New ChainMap with a new map followed by all previous maps. If no
        map is provided, an empty dict is used.
        '''
        if m is None:
            m = {}
        return self.__class__(m, *self.maps) 
Example 45
Project: Repobot   Author: Desgard   File: misc.py    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 46
Project: JukeBox   Author: gauravsarkar97   File: compat.py    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 47
Project: JukeBox   Author: gauravsarkar97   File: compat.py    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 48
Project: JukeBox   Author: gauravsarkar97   File: compat.py    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 49
Project: JukeBox   Author: gauravsarkar97   File: compat.py    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 50
Project: JukeBox   Author: gauravsarkar97   File: compat.py    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 51
Project: chattR   Author: patrickstocklin   File: compat.py    GNU General Public License v2.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 52
Project: chattR   Author: patrickstocklin   File: compat.py    GNU General Public License v2.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 53
Project: chattR   Author: patrickstocklin   File: compat.py    GNU General Public License v2.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 54
Project: chattR   Author: patrickstocklin   File: compat.py    GNU General Public License v2.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 55
Project: chattR   Author: patrickstocklin   File: compat.py    GNU General Public License v2.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 56
Project: bot   Author: python-discord   File: helpers.py    MIT License 5 votes vote down vote up
def __init__(self, roles: Optional[Iterable[MockRole]] = None, **kwargs) -> None:
        default_kwargs = {'id': next(self.discord_id), 'members': []}
        super().__init__(spec_set=guild_instance, **collections.ChainMap(kwargs, default_kwargs))

        self.roles = [MockRole(name="@everyone", position=1, id=0)]
        if roles:
            self.roles.extend(roles)


# Create a Role instance to get a realistic Mock of `discord.Role` 
Example 57
Project: bot   Author: python-discord   File: helpers.py    MIT License 5 votes vote down vote up
def __init__(self, **kwargs) -> None:
        default_kwargs = {'id': next(self.discord_id), 'name': 'role', 'position': 1}
        super().__init__(spec_set=role_instance, **collections.ChainMap(kwargs, default_kwargs))

        if 'mention' not in kwargs:
            self.mention = f'&{self.name}' 
Example 58
Project: bot   Author: python-discord   File: helpers.py    MIT License 5 votes vote down vote up
def __init__(self, roles: Optional[Iterable[MockRole]] = None, **kwargs) -> None:
        default_kwargs = {'name': 'member', 'id': next(self.discord_id), 'bot': False}
        super().__init__(spec_set=member_instance, **collections.ChainMap(kwargs, default_kwargs))

        self.roles = [MockRole(name="@everyone", position=1, id=0)]
        if roles:
            self.roles.extend(roles)

        if 'mention' not in kwargs:
            self.mention = f"@{self.name}"


# Create a User instance to get a realistic Mock of `discord.User` 
Example 59
Project: bot   Author: python-discord   File: helpers.py    MIT License 5 votes vote down vote up
def __init__(self, **kwargs) -> None:
        default_kwargs = {'name': 'user', 'id': next(self.discord_id), 'bot': False}
        super().__init__(spec_set=user_instance, **collections.ChainMap(kwargs, default_kwargs))

        if 'mention' not in kwargs:
            self.mention = f"@{self.name}"


# Create a Bot instance to get a realistic MagicMock of `discord.ext.commands.Bot` 
Example 60
Project: bot   Author: python-discord   File: helpers.py    MIT License 5 votes vote down vote up
def __init__(self, name: str = 'channel', channel_id: int = 1, **kwargs) -> None:
        default_kwargs = {'id': next(self.discord_id), 'name': 'channel', 'guild': MockGuild()}
        super().__init__(spec_set=channel_instance, **collections.ChainMap(kwargs, default_kwargs))

        if 'mention' not in kwargs:
            self.mention = f"#{self.name}"


# Create a Message instance to get a realistic MagicMock of `discord.Message` 
Example 61
Project: Flask_Blog   Author: sugarguo   File: compat.py    GNU General Public License v3.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 62
Project: Flask_Blog   Author: sugarguo   File: compat.py    GNU General Public License v3.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 63
Project: Flask_Blog   Author: sugarguo   File: compat.py    GNU General Public License v3.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 64
Project: Flask_Blog   Author: sugarguo   File: compat.py    GNU General Public License v3.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 65
Project: Flask_Blog   Author: sugarguo   File: compat.py    GNU General Public License v3.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 66
Project: NiujiaoDebugger   Author: MrSrc   File: string.py    GNU General Public License v3.0 5 votes vote down vote up
def substitute(*args, **kws):
        if not args:
            raise TypeError("descriptor 'substitute' of 'Template' object "
                            "needs an argument")
        self, *args = args  # allow the "self" keyword be passed
        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:
                return str(mapping[named])
            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 67
Project: NiujiaoDebugger   Author: MrSrc   File: string.py    GNU General Public License v3.0 5 votes vote down vote up
def safe_substitute(*args, **kws):
        if not args:
            raise TypeError("descriptor 'safe_substitute' of 'Template' object "
                            "needs an argument")
        self, *args = args  # allow the "self" keyword be passed
        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):
            named = mo.group('named') or mo.group('braced')
            if named is not None:
                try:
                    return str(mapping[named])
                except KeyError:
                    return mo.group()
            if mo.group('escaped') is not None:
                return self.delimiter
            if mo.group('invalid') is not None:
                return mo.group()
            raise ValueError('Unrecognized named group in pattern',
                             self.pattern)
        return self.pattern.sub(convert, self.template)



########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class

# The hard parts are reused from the C implementation.  They're exposed as "_"
# prefixed methods of str.

# The overall parser is implemented in _string.formatter_parser.
# The field name parser is implemented in _string.formatter_field_name_split 
Example 68
Project: NiujiaoDebugger   Author: MrSrc   File: test_collections.py    GNU General Public License v3.0 5 votes vote down vote up
def test_dict_protocol(self):
        self._superset_test(UserDict, dict)


################################################################################
### ChainMap (helper class for configparser and the string module)
################################################################################ 
Example 69
Project: NiujiaoDebugger   Author: MrSrc   File: test_collections.py    GNU General Public License v3.0 5 votes vote down vote up
def test_constructor(self):
        self.assertEqual(ChainMap().maps, [{}])                        # no-args --> one new dict
        self.assertEqual(ChainMap({1:2}).maps, [{1:2}])                # 1 arg --> list 
Example 70
Project: NiujiaoDebugger   Author: MrSrc   File: test_collections.py    GNU General Public License v3.0 5 votes vote down vote up
def test_bool(self):
        self.assertFalse(ChainMap())
        self.assertFalse(ChainMap({}, {}))
        self.assertTrue(ChainMap({1:2}, {}))
        self.assertTrue(ChainMap({}, {1:2})) 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: test_collections.py    GNU General Public License v3.0 5 votes vote down vote up
def test_dict_coercion(self):
        d = ChainMap(dict(a=1, b=2), dict(b=20, c=30))
        self.assertEqual(dict(d), dict(a=1, b=2, c=30))
        self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30)) 
Example 72
Project: NiujiaoDebugger   Author: MrSrc   File: test_pprint.py    GNU General Public License v3.0 5 votes vote down vote up
def test_chainmap(self):
        d = collections.ChainMap()
        self.assertEqual(pprint.pformat(d, width=1), "ChainMap({})")
        words = 'the quick brown fox jumped over a lazy dog'.split()
        items = list(zip(words, itertools.count()))
        d = collections.ChainMap(dict(items))
        self.assertEqual(pprint.pformat(d),
"""\
ChainMap({'a': 6,
          'brown': 2,
          'dog': 8,
          'fox': 3,
          'jumped': 4,
          'lazy': 7,
          'over': 5,
          'quick': 1,
          'the': 0})""")
        d = collections.ChainMap(dict(items), collections.OrderedDict(items))
        self.assertEqual(pprint.pformat(d),
"""\
ChainMap({'a': 6,
          'brown': 2,
          'dog': 8,
          'fox': 3,
          'jumped': 4,
          'lazy': 7,
          'over': 5,
          'quick': 1,
          'the': 0},
         OrderedDict([('the', 0),
                      ('quick', 1),
                      ('brown', 2),
                      ('fox', 3),
                      ('jumped', 4),
                      ('over', 5),
                      ('a', 6),
                      ('lazy', 7),
                      ('dog', 8)]))""") 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: test_pickle.py    GNU General Public License v3.0 5 votes vote down vote up
def get_dispatch_table(self):
        return collections.ChainMap({}, pickle.dispatch_table) 
Example 74
Project: NiujiaoDebugger   Author: MrSrc   File: test_pickle.py    GNU General Public License v3.0 5 votes vote down vote up
def get_dispatch_table(self):
            return collections.ChainMap({}, pickle.dispatch_table) 
Example 75
Project: NiujiaoDebugger   Author: MrSrc   File: test_typing.py    GNU General Public License v3.0 5 votes vote down vote up
def test_chainmap_instantiation(self):
        self.assertIs(type(typing.ChainMap()), collections.ChainMap)
        self.assertIs(type(typing.ChainMap[KT, VT]()), collections.ChainMap)
        self.assertIs(type(typing.ChainMap[str, int]()), collections.ChainMap)
        class CM(typing.ChainMap[KT, VT]): ...
        self.assertIs(type(CM[int, str]()), CM) 
Example 76
Project: Health-Checker   Author: KriAga   File: compat.py    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 77
Project: Health-Checker   Author: KriAga   File: compat.py    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 78
Project: Health-Checker   Author: KriAga   File: compat.py    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 79
Project: cree-sro-syllabics   Author: eddieantonio   File: cree_sro_syllabics.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def transcode_sro_word_to_syllabics(sro_word: str, hyphen: str, sandhi: bool) -> str:
    """
    Transcribes one word at a time.
    """

    to_transcribe = sro_word.lower().\
        translate(TRANSLATE_ALT_FORMS)

    # Augment the lookup table with an entry for «-» so that we can replace
    # all instances of '-' easily.
    lookup = ChainMap({
        '-': hyphen
    }, sro2syllabics_lookup)

    parts = []

    match = sro_pattern.match(to_transcribe)
    while match:
        onset, vowel = match.groups()
        if sandhi and onset is not None:
            if onset.startswith('h'):
                # Special case for /hw?-V/ sandhi case:
                # add the 'h'/ᐦ syllabic, then proceed with the w?V as normal:
                parts.append('ᐦ')
                onset = onset[1:]
            # Apply sandhi rule
            assert vowel is not None
            syllable = onset + vowel
            next_syllable_pos = match.end()
        elif onset is not None:
            # Not Sandhi -- let's consume the onset (consonant)
            # Do NOT consume the labialized w!
            syllable = 'w' if onset == 'w' else onset.rstrip('w')
            # Skip the first consonant.
            next_syllable_pos = len(syllable)
            assert syllable in CONSONANT
        else:
            syllable = match.group(0)
            next_syllable_pos = match.end()

        # Get the syllabic
        syllabic = lookup[syllable]
        parts.append(syllabic)

        # Chop off transcribed part
        to_transcribe = to_transcribe[next_syllable_pos:]
        match = sro_pattern.match(to_transcribe)

    # Special-case word-final 'hk': we did not convert it in the above loop,
    # because it can only happen at the end of words, and if we did convert it
    # in the prior loop, it would convert '-ihkwê-' -> 'ᐃᕽᐍ' instead of 'ᐃᐦᑵ'
    # as intended. We know the end of the word is 'hk' because it got
    # converted to «ᐦ» followed by «ᐠ».
    if parts[-2:] == ['ᐦ', 'ᐠ']:
        parts[-2:] = [sro2syllabics_lookup['hk']]

    assert to_transcribe == '', 'could not transcribe %r' % (to_transcribe)
    return ''.join(parts) 
Example 80
Project: NiujiaoDebugger   Author: MrSrc   File: test_functools.py    GNU General Public License v3.0 4 votes vote down vote up
def test_compose_mro(self):
        # None of the examples in this test depend on haystack ordering.
        c = collections.abc
        mro = functools._compose_mro
        bases = [c.Sequence, c.MutableMapping, c.Mapping, c.Set]
        for haystack in permutations(bases):
            m = mro(dict, haystack)
            self.assertEqual(m, [dict, c.MutableMapping, c.Mapping,
                                 c.Collection, c.Sized, c.Iterable,
                                 c.Container, object])
        bases = [c.Container, c.Mapping, c.MutableMapping, collections.OrderedDict]
        for haystack in permutations(bases):
            m = mro(collections.ChainMap, haystack)
            self.assertEqual(m, [collections.ChainMap, c.MutableMapping, c.Mapping,
                                 c.Collection, c.Sized, c.Iterable,
                                 c.Container, object])

        # If there's a generic function with implementations registered for
        # both Sized and Container, passing a defaultdict to it results in an
        # ambiguous dispatch which will cause a RuntimeError (see
        # test_mro_conflicts).
        bases = [c.Container, c.Sized, str]
        for haystack in permutations(bases):
            m = mro(collections.defaultdict, [c.Sized, c.Container, str])
            self.assertEqual(m, [collections.defaultdict, dict, c.Sized,
                                 c.Container, object])

        # MutableSequence below is registered directly on D. In other words, it
        # precedes MutableMapping which means single dispatch will always
        # choose MutableSequence here.
        class D(collections.defaultdict):
            pass
        c.MutableSequence.register(D)
        bases = [c.MutableSequence, c.MutableMapping]
        for haystack in permutations(bases):
            m = mro(D, bases)
            self.assertEqual(m, [D, c.MutableSequence, c.Sequence, c.Reversible,
                                 collections.defaultdict, dict, c.MutableMapping, c.Mapping,
                                 c.Collection, c.Sized, c.Iterable, c.Container,
                                 object])

        # Container and Callable are registered on different base classes and
        # a generic function supporting both should always pick the Callable
        # implementation if a C instance is passed.
        class C(collections.defaultdict):
            def __call__(self):
                pass
        bases = [c.Sized, c.Callable, c.Container, c.Mapping]
        for haystack in permutations(bases):
            m = mro(C, haystack)
            self.assertEqual(m, [C, c.Callable, collections.defaultdict, dict, c.Mapping,
                                 c.Collection, c.Sized, c.Iterable,
                                 c.Container, object])