Python types.MappingProxyType() Examples

The following are code examples for showing how to use types.MappingProxyType(). 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: fs_image   Author: facebookincubator   File: subvolume_set.py    MIT License 6 votes vote down vote up
def freeze(self, *, _memo) -> 'SubvolumeSet':
        '''
        Return a recursively immutable copy of `self`, replacing all
        `IncompleteInode`s by `Inode`s, and checking that all inode metadata
        are populated.  Correctly resolving cloned extents has to happen at
        the level of the `SubvolumeSet`.
        '''
        id_to_chunks = dict(extents_to_chunks_with_clones(
            list(itertools.chain.from_iterable(
                subvol._inode_ids_and_extents()
                    for subvol in self.uuid_to_subvolume.values()
            ))
        ))
        return type(self)(
            uuid_to_subvolume=MappingProxyType({
                uuid: freeze(subvol, _memo=_memo, id_to_chunks=id_to_chunks)
                    for uuid, subvol in self.uuid_to_subvolume.items()
            }),
            name_uuid_prefix_counts=freeze(
                self.name_uuid_prefix_counts, _memo=_memo,
            ),
        ) 
Example 2
Project: adh6   Author: bonnetn   File: context.py    GNU General Public License v3.0 6 votes vote down vote up
def build_context(ctx: MappingProxyType = None, session=None, admin=None, testing=None, request_id=None):
    """

    :rtype:
    """
    new_fields = {
        CTX_SQL_SESSION: session,
        CTX_ADMIN: admin,
        CTX_TESTING: testing,
        CTX_REQUEST_ID: request_id,
    }
    if ctx is None:
        return MappingProxyType(new_fields)

    old_fields = {k: v for k, v in ctx.items() if v is not None}  # Remove None fields.

    merged = {**new_fields, **old_fields}  # Merge old and new context, with priority for the new one.

    return MappingProxyType(merged) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_builtin.py    GNU General Public License v3.0 6 votes vote down vote up
def test_bad_args(self):
        with self.assertRaises(TypeError):
            type()
        with self.assertRaises(TypeError):
            type('A', ())
        with self.assertRaises(TypeError):
            type('A', (), {}, ())
        with self.assertRaises(TypeError):
            type('A', (), dict={})
        with self.assertRaises(TypeError):
            type('A', [], {})
        with self.assertRaises(TypeError):
            type('A', (), types.MappingProxyType({}))
        with self.assertRaises(TypeError):
            type('A', (None,), {})
        with self.assertRaises(TypeError):
            type('A', (bool,), {})
        with self.assertRaises(TypeError):
            type('A', (int, str), {}) 
Example 4
Project: aiohttp_admin   Author: aio-libs   File: utils.py    Apache License 2.0 6 votes vote down vote up
def validate_query(query, possible_columns):
    q = validate_query_structure(query)
    sort_field = q.get('_sortField')

    filters = q.get('_filters', [])
    columns = [field_name for field_name in filters]

    if sort_field is not None:
        columns.append(sort_field)

    not_valid = set(columns).difference(
        possible_columns + [MULTI_FIELD_TEXT_QUERY])
    if not_valid:
        column_list = ', '.join(not_valid)
        msg = 'Columns: {} do not present in resource'.format(column_list)
        raise JsonValidaitonError(msg)
    return MappingProxyType(q) 
Example 5
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_float(self):
        """Tests openexchangerate.OpenExchangeRateClient.historical()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               self._date,
                               body=self._FIXTURE_LATEST)
        historical = client.historical(self._date)

        self.assertIsInstance(historical, tuple)
        self.assertIsInstance(historical.dict, dict)
        self.assertIsInstance(historical.frozendict, frozendict)

        self.assertIn('AED', historical.dict)
        self.assertEqual(historical.dict['AED'], 3.666311)
        self.assertIn('AFN', historical.dict)
        self.assertEqual(historical.dict['AFN'], 51.2281)
        self.assertIn('ALL', historical.dict)
        self.assertEqual(historical.dict['ALL'], 104.748751)
        self.assertIn('USD', historical.dict)
        self.assertEqual(historical.dict['USD'], 1.0) 
Example 6
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_decimal(self):
        """Tests openexchangerate.OpenExchangeRateClient.historical()."""
        client = openexchangerate.OpenExchangeRates('DUMMY_API_KEY',
                                                           use_float=False)
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               self._date,
                               body=self._FIXTURE_LATEST)
        historical = client.historical(self._date)

        self.assertIsInstance(historical, tuple)
        self.assertIsInstance(historical.dict, dict)
        self.assertIsInstance(historical.frozendict, frozendict)

        self.assertIn('AED', historical.dict)
        self.assertEqual(historical.dict['AED'], decimal.Decimal('3.666311'))
        self.assertIn('AFN', historical.dict)
        self.assertEqual(historical.dict['AFN'], decimal.Decimal('51.2281'))
        self.assertIn('ALL', historical.dict)
        self.assertEqual(historical.dict['ALL'], decimal.Decimal('104.748751'))
        self.assertIn('USD', historical.dict)
        self.assertEqual(historical.dict['USD'], decimal.Decimal('1')) 
Example 7
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_currencies_float(self):
        """Tests openexchangerate.OpenExchangeRateClient.currencies()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_CURRENCIES,
                               body=self._FIXTURE_CURRENCIES)
        currencies = client.currencies()

        self.assertIsInstance(currencies, tuple)
        self.assertIsInstance(currencies.dict, dict)
        self.assertIsInstance(currencies.frozendict, frozendict)

        self.assertIn('AED', currencies.dict)
        self.assertIn('AFN', currencies.dict)
        self.assertIn('ALL', currencies.dict)
        self.assertIn('USD', currencies.dict) 
Example 8
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_latest_float(self):
        """Tests openexchangerate.OpenExchangeRateClient.latest()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        latest = client.latest()

        self.assertIsInstance(latest, tuple)
        self.assertIsInstance(latest.dict, dict)
        self.assertIsInstance(latest.frozendict, frozendict)

        self.assertIn('AED', latest.dict)
        self.assertEqual(latest.dict['AED'], 3.666311)
        self.assertIn('AFN', latest.dict)
        self.assertEqual(latest.dict['AFN'], 51.2281)
        self.assertIn('ALL', latest.dict)
        self.assertEqual(latest.dict['ALL'], 104.748751)
        self.assertIn('USD', latest.dict)
        self.assertEqual(latest.dict['USD'], 1.0) 
Example 9
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_latest_decimal(self):
        """Tests openexchangerate.OpenExchangeRateClient.latest()."""
        client = openexchangerate.OpenExchangeRates('DUMMY_API_KEY',
                                                           use_float=False)
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        latest = client.latest()

        self.assertIsInstance(latest, tuple)
        self.assertIsInstance(latest.dict, dict)
        self.assertIsInstance(latest.frozendict, frozendict)

        self.assertIn('AED', latest.dict)
        self.assertEqual(latest.dict['AED'], decimal.Decimal('3.666311'))
        self.assertIn('AFN', latest.dict)
        self.assertEqual(latest.dict['AFN'], decimal.Decimal('51.2281'))
        self.assertIn('ALL', latest.dict)
        self.assertEqual(latest.dict['ALL'], decimal.Decimal('104.748751'))
        self.assertIn('USD', latest.dict)
        self.assertEqual(latest.dict['USD'], decimal.Decimal('1')) 
Example 10
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_with_local_base_conversion_float(self):
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)), local_base='AED')
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               self._date,
                               body=self._FIXTURE_HISTORICAL)
        historical_conversion = client.historical(self._date)

        self.assertIsInstance(historical_conversion, tuple)
        self.assertIsInstance(historical_conversion.dict, dict)
        self.assertIsInstance(historical_conversion.frozendict, frozendict)

        self.assertEqual(historical_conversion.dict['AED'], 1.0)
        self.assertEqual(historical_conversion.dict['AFN'], 13.97265535)
        self.assertEqual(historical_conversion.dict['ALL'], 28.57061253)
        self.assertEqual(historical_conversion.dict['USD'], 0.27275373) 
Example 11
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_with_local_base_conversion_decimal(self):
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', use_float=False, local_base='AED')
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               "2012-12-12",
                               body=self._FIXTURE_HISTORICAL)
        histo_cn = client.historical("2012-12-12")

        self.assertIsInstance(histo_cn, tuple)
        self.assertIsInstance(histo_cn.dict, dict)
        self.assertIsInstance(histo_cn.frozendict, frozendict)

        self.assertEqual(histo_cn.dict['AED'], decimal.Decimal('1.0'))
        self.assertEqual(histo_cn.dict['AFN'], decimal.Decimal('13.97265535'))
        self.assertEqual(histo_cn.dict['ALL'], decimal.Decimal('28.57061253'))
        self.assertEqual(histo_cn.dict['USD'], decimal.Decimal('0.27275373')) 
Example 12
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_contextmanager(self):
        """Tests openexchangerate.OpenExchangeRateClient.latest()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        with client as exchange_prices:
            self.assertIsInstance(exchange_prices, tuple)
            self.assertIsInstance(exchange_prices.dict, dict)
            self.assertIsInstance(exchange_prices.frozendict, frozendict)

            self.assertIn('AED', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['AED'], 3.666311)
            self.assertIn('AFN', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['AFN'], 51.2281)
            self.assertIn('ALL', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['ALL'], 104.748751)
            self.assertIn('USD', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['USD'], 1.0) 
Example 13
Project: openexchangerate   Author: juancarlospaco   File: openexchangerate.py    GNU General Public License v3.0 6 votes vote down vote up
def html(self, prices_data_dict: dict):
        names_get = self.currencies().frozendict.get
        prices = tuple(enumerate(prices_data_dict.items()))
        row = "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>"
        h = "<thead><th>#</th><th>Code</th><th>Price</th><th>Name</th></thead>"

        rows = [row.format(index, mony[0], mony[1], names_get(mony[0], "???"))
                for index, mony in prices
                if mony[0] not in ("EUR", "USD")]  # Skip Dollar and Euro.

        prio = [row.format(index, mony[0], mony[1], names_get(mony[0], "???"))
                for index, mony in prices
                if mony[0] in ("EUR", "USD")]  # Move Dollar and Euro at Top.

        return (f"<table>{ h if self.html_table_header else ''}"
                f"<tbody>{' '.join(prio + rows)}</tbody></table>") 
Example 14
Project: pycoalaip   Author: COALAIP   File: data_formats.py    Apache License 2.0 6 votes vote down vote up
def _make_context_immutable(context):
    """Best effort attempt at turning a properly formatted context
    (either a string, dict, or array of strings and dicts) into an
    immutable data structure.

    If we get an array, make it immutable by creating a tuple; if we get
    a dict, copy it into a MappingProxyType. Otherwise, return as-is.
    """
    def make_immutable(val):
        if isinstance(val, Mapping):
            return MappingProxyType(val)
        else:
            return val

    if not isinstance(context, (str, Mapping)):
        try:
            return tuple([make_immutable(val) for val in context])
        except TypeError:
            pass
    return make_immutable(context) 
Example 15
Project: edgedb   Author: edgedb   File: lexer.py    Apache License 2.0 6 votes vote down vote up
def __init_subclass__(cls):
        if not hasattr(cls, 'states'):
            return

        re_states = {}
        for state, rules in cls.states.items():
            res = []
            for rule in rules:
                if cls.asbytes:
                    res.append(b'(?P<%b>%b)' % (rule.id.encode(), rule.regexp))
                else:
                    res.append('(?P<{}>{})'.format(rule.id, rule.regexp))

            if cls.asbytes:
                res.append(b'(?P<err>.)')
            else:
                res.append('(?P<err>.)')

            if cls.asbytes:
                full_re = b' | '.join(res)
            else:
                full_re = ' | '.join(res)
            re_states[state] = re.compile(full_re, cls.RE_FLAGS)

        cls.re_states = types.MappingProxyType(re_states) 
Example 16
Project: fs_image   Author: facebookincubator   File: subvolume.py    MIT License 5 votes vote down vote up
def freeze(
        self,
        *,
        _memo,
        id_to_chunks: Optional[Mapping[InodeID, Sequence['Chunk']]]=None,
    ):
        '''
        Returns a recursively immutable copy of `self`, replacing
        `IncompleteInode`s by `Inode`s, using the provided `id_to_chunks` to
        populate them with `Chunk`s instead of `Extent`s.

        If `id_to_chunks` is omitted, we'll detect clones only within `self`.

        IMPORTANT: Our lookups assume that the `id_to_chunks` has the
        pre-`freeze` variants of the `InodeID`s.
        '''
        if id_to_chunks is None:
            id_to_chunks = dict(extents_to_chunks_with_clones(
                list(self._inode_ids_and_extents()),
            ))
        return type(self)(
            id_map=freeze(self.id_map, _memo=_memo),
            id_to_inode=MappingProxyType({
                freeze(id, _memo=_memo):
                        freeze(ino, _memo=_memo, chunks=id_to_chunks.get(id))
                    for id, ino in self.id_to_inode.items()
            }),
        ) 
Example 17
Project: fs_image   Author: facebookincubator   File: freeze.py    MIT License 5 votes vote down vote up
def freeze(obj, *, _memo=None, **kwargs):
    # Don't bother memoizing primitive types
    if isinstance(obj, (bytes, Enum, float, int, str, type(None))):
        return obj

    if _memo is None:
        _memo = {}

    if id(obj) in _memo:  # Already frozen?
        return _memo[id(obj)]

    if hasattr(obj, 'freeze'):
        frozen = obj.freeze(_memo=_memo, **kwargs)
    else:
        # At the moment, I don't have a need for passing extra data into
        # items that live inside containers.  If we're relaxing this, just
        # be sure to add `**kwargs` to each `freeze()` call below.
        assert kwargs == {}, kwargs
        # This is a lame-o way of identifying `NamedTuple`s. Using
        # `deepfrozen` would avoid this kludge.
        if (
            isinstance(obj, tuple) and hasattr(obj, '_replace') and
            hasattr(obj, '_fields') and hasattr(obj, '_make')
        ):
            frozen = obj._make(freeze(i, _memo=_memo) for i in obj)
        elif isinstance(obj, (list, tuple)):
            frozen = tuple(freeze(i, _memo=_memo) for i in obj)
        elif isinstance(obj, dict):
            frozen = MappingProxyType({
                freeze(k, _memo=_memo): freeze(v, _memo=_memo)
                    for k, v in obj.items()
            })
        elif isinstance(obj, (set, frozenset)):
            frozen = frozenset(freeze(i, _memo=_memo) for i in obj)
        else:
            raise NotImplementedError(type(obj))

    _memo[id(obj)] = frozen
    return frozen 
Example 18
Project: fs_image   Author: facebookincubator   File: test_freeze.py    MIT License 5 votes vote down vote up
def test_memo(self):
        l = []
        memo = {}
        d = {'inner': {1: l, 2: l}}
        fd = freeze(d, _memo=memo)
        self.assertEqual({'inner': {1: (), 2: ()}}, fd)
        self.assertIsInstance(fd, MappingProxyType)
        self.assertIsInstance(fd['inner'], MappingProxyType)
        self.assertIs(fd['inner'][1], fd['inner'][2])
        self.assertEqual({id(d), id(d['inner']), id(l)}, set(memo.keys())) 
Example 19
Project: fs_image   Author: facebookincubator   File: test_freeze.py    MIT License 5 votes vote down vote up
def test_containers(self):
        f = freeze([([]), {5}, frozenset([7]), {'a': 'b'}])
        self.assertEqual(((()), {5}, {7}, {'a': 'b'}), f)
        self.assertEqual(
            [tuple, frozenset, frozenset, MappingProxyType],
            [type(i) for i in f],
        ) 
Example 20
Project: sic   Author: Yanixos   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 21
Project: adh6   Author: bonnetn   File: context.py    GNU General Public License v3.0 5 votes vote down vote up
def log_extra(context: MappingProxyType, **extra_fields):
    admin_login = None
    if context.get(CTX_ADMIN):
        admin_login = context.get(CTX_ADMIN).login

    infos = {
        'request_uuid': context.get(CTX_REQUEST_ID),
        'admin': admin_login,
        'testing': str(context.get(CTX_TESTING) or False),
    }
    return {
        'extra': {**infos, **extra_fields},
    } 
Example 22
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    Apache License 2.0 5 votes vote down vote up
def save_mappingproxy(self, obj):
            self.save_reduce(types.MappingProxyType, (dict(obj),), obj=obj) 
Example 23
Project: jawfish   Author: war-and-code   File: inspect.py    MIT License 5 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        '''Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        '''

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    if kind < top_kind:
                        msg = 'wrong parameter order: {} before {}'
                        msg = msg.format(top_kind, param.kind)
                        raise ValueError(msg)
                    else:
                        top_kind = kind

                    name = param.name
                    if name is None:
                        name = str(idx)
                        param = param.replace(name=name)

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)
                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 24
Project: Repobot   Author: Desgard   File: _signatures.py    MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example 25
Project: tangent   Author: google   File: funcsigs.py    Apache License 2.0 5 votes vote down vote up
def parameters(self):
    try:
      return types.MappingProxyType(self._parameters)
    except AttributeError:
      return OrderedDict(self._parameters.items()) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: headerregistry.py    GNU General Public License v3.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: dataclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, default, default_factory, init, repr, hash, compare,
                 metadata):
        self.name = None
        self.type = None
        self.default = default
        self.default_factory = default_factory
        self.init = init
        self.repr = repr
        self.hash = hash
        self.compare = compare
        self.metadata = (_EMPTY_METADATA
                         if metadata is None or len(metadata) == 0 else
                         types.MappingProxyType(metadata))
        self._field_type = None 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 29
Project: discord.py   Author: Rapptz   File: enums.py    MIT License 5 votes vote down vote up
def __members__(cls):
        return types.MappingProxyType(cls._enum_member_map_) 
Example 30
Project: discord.py   Author: Rapptz   File: bot.py    MIT License 5 votes vote down vote up
def cogs(self):
        """Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to cog."""
        return types.MappingProxyType(self.__cogs)

    # extensions 
Example 31
Project: discord.py   Author: Rapptz   File: bot.py    MIT License 5 votes vote down vote up
def extensions(self):
        """Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to extension."""
        return types.MappingProxyType(self.__extensions)

    # help command stuff 
Example 32
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 33
Project: python-netsurv   Author: sofia-netsurv   File: _compat.py    MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 34
Project: python-netsurv   Author: sofia-netsurv   File: _compat.py    MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 35
Project: bob   Author: BobBuildTool   File: stringparser.py    GNU General Public License v3.0 5 votes vote down vote up
def inspect(self):
        return MappingProxyType(self.data) 
Example 36
Project: rekt   Author: dillonhicks   File: utils.py    Apache License 2.0 5 votes vote down vote up
def read_only_dict(mapping):
    return types.MappingProxyType(mapping) 
Example 37
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: __init__.py    MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example 38
Project: unhuman-resources   Author: agajdosi   File: web_request.py    GNU General Public License v3.0 5 votes vote down vote up
def cookies(self) -> Mapping[str, str]:
        """Return request cookies.

        A read-only dictionary-like object.
        """
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()}) 
Example 39
Project: unhuman-resources   Author: agajdosi   File: client_reqrep.py    GNU General Public License v3.0 5 votes vote down vote up
def content_disposition(self) -> Optional[ContentDisposition]:
        raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
        if raw is None:
            return None
        disposition_type, params_dct = multipart.parse_content_disposition(raw)
        params = MappingProxyType(params_dct)
        filename = multipart.content_disposition_filename(params)
        return ContentDisposition(disposition_type, params, filename) 
Example 40
Project: unhuman-resources   Author: agajdosi   File: web_urldispatcher.py    GNU General Public License v3.0 5 votes vote down vote up
def named_resources(self) -> Mapping[str, AbstractResource]:
        return MappingProxyType(self._named_resources) 
Example 41
Project: unhuman-resources   Author: agajdosi   File: _compat.py    GNU General Public License v3.0 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 42
Project: unhuman-resources   Author: agajdosi   File: web_request.py    GNU General Public License v3.0 5 votes vote down vote up
def cookies(self) -> Mapping[str, str]:
        """Return request cookies.

        A read-only dictionary-like object.
        """
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()}) 
Example 43
Project: unhuman-resources   Author: agajdosi   File: client_reqrep.py    GNU General Public License v3.0 5 votes vote down vote up
def content_disposition(self) -> Optional[ContentDisposition]:
        raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
        if raw is None:
            return None
        disposition_type, params_dct = multipart.parse_content_disposition(raw)
        params = MappingProxyType(params_dct)
        filename = multipart.content_disposition_filename(params)
        return ContentDisposition(disposition_type, params, filename) 
Example 44
Project: unhuman-resources   Author: agajdosi   File: web_urldispatcher.py    GNU General Public License v3.0 5 votes vote down vote up
def named_resources(self) -> Mapping[str, AbstractResource]:
        return MappingProxyType(self._named_resources) 
Example 45
Project: unhuman-resources   Author: agajdosi   File: _compat.py    GNU General Public License v3.0 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 46
Project: XMorbid   Author: NMTech0x90   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 47
Project: open-recipe   Author: dspray95   File: _compat.py    The Unlicense 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 48
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_latest_with_local_base_conversion_decimal(self):
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', use_float=False, local_base='AED')
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        latest_cn = client.latest()

        self.assertIsInstance(latest_cn, tuple)
        self.assertIsInstance(latest_cn.dict, dict)
        self.assertIsInstance(latest_cn.frozendict, frozendict)

        self.assertEqual(latest_cn.dict['AED'], decimal.Decimal('1'))
        self.assertEqual(latest_cn.dict['AFN'], decimal.Decimal('13.97265535'))
        self.assertEqual(latest_cn.dict['ALL'], decimal.Decimal('28.57061253'))
        self.assertEqual(latest_cn.dict['USD'], decimal.Decimal('0.27275373')) 
Example 49
Project: openexchangerate   Author: juancarlospaco   File: openexchangerate.py    GNU General Public License v3.0 5 votes vote down vote up
def _parsed_response(self, response):
        data = loads(response, parse_int=self.tipe,
                     parse_float=self.tipe)['rates']

        if self.local_base:
            data = self._local_conversion(data, self.local_base)

        return namedtuple(
            "OpenExchangeRates", "dict frozendict html namedtuple")(
            data, frozendict(data), self.html(data),
            namedtuple("OpenExchangeRates", data.keys())(*data.values())) 
Example 50
Project: Blockly-rduino-communication   Author: technologiescollege   File: headerregistry.py    GNU General Public License v3.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example 51
Project: Blockly-rduino-communication   Author: technologiescollege   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 52
Project: edgedb   Author: edgedb   File: functions.py    Apache License 2.0 5 votes vote down vote up
def find_named_only(
        self,
        schema: s_schema.Schema
    ) -> Mapping[str, Parameter]:
        named = {}
        for param in self.objects(schema):
            if param.get_kind(schema) is ft.ParameterKind.NAMED_ONLY:
                named[param.get_shortname(schema)] = param

        return types.MappingProxyType(named) 
Example 53
Project: edgedb   Author: edgedb   File: types.py    Apache License 2.0 5 votes vote down vote up
def create(
        cls: typing.Type[BaseTuple_T],
        schema: s_schema.Schema,
        *,
        name: Optional[s_name.Name] = None,
        id: Union[uuid.UUID, so.NoDefaultT] = so.NoDefault,
        element_types: Mapping[str, Type],
        named: bool = False,
        **kwargs,
    ) -> BaseTuple_T:
        element_types = types.MappingProxyType(element_types)
        if id is so.NoDefault:
            id_str = ','.join(
                f'{n}:{st.id}' for n, st in element_types.items())
            id_str = f'tuple-{id_str}'
            id = generate_type_id(id_str)

        if name is None:
            if named:
                st_names = ','.join(f'{sn}:={st.get_name(schema)}'
                                    for sn, st in element_types.items())
            else:
                st_names = ','.join(st.get_name(schema)
                                    for st in element_types.values())
            name = s_name.SchemaName(
                module='std',
                name=f'tuple<{st_names}>')

        return super()._create(
            schema, id=id, name=name, named=named,
            element_types=element_types, **kwargs) 
Example 54
Project: edgedb   Author: edgedb   File: types.py    Apache License 2.0 5 votes vote down vote up
def __setstate__(self, state: Dict[str, Any]) -> None:
        state['element_types'] = types.MappingProxyType(state['element_types'])
        self.__dict__.update(state)


# Breaking Liskov Substitution Principle 
Example 55
Project: mlens   Author: flennerhag   File: funcsigs.py    MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example 56
Project: 2015cdb_g4   Author: 40223208   File: inspect.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        '''Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        '''

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    if kind < top_kind:
                        msg = 'wrong parameter order: {} before {}'
                        msg = msg.format(top_kind, param.kind)
                        raise ValueError(msg)
                    else:
                        top_kind = kind

                    name = param.name
                    if name is None:
                        name = str(idx)
                        param = param.replace(name=name)

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)
                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 57
Project: jikken   Author: outcastofmusic   File: experiment.py    MIT License 5 votes vote down vote up
def variables(self):
        return MappingProxyType(self._variables) 
Example 58
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: headerregistry.py    GNU General Public License v2.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example 59
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: dataclasses.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, default, default_factory, init, repr, hash, compare,
                 metadata):
        self.name = None
        self.type = None
        self.default = default
        self.default_factory = default_factory
        self.init = init
        self.repr = repr
        self.hash = hash
        self.compare = compare
        self.metadata = (_EMPTY_METADATA
                         if metadata is None else
                         types.MappingProxyType(metadata))
        self._field_type = None 
Example 60
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: _compat.py    GNU General Public License v2.0 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 61
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: enum.py    GNU General Public License v2.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 62
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_pprint.py    GNU General Public License v2.0 5 votes vote down vote up
def test_mapping_proxy(self):
        words = 'the quick brown fox jumped over a lazy dog'.split()
        d = dict(zip(words, itertools.count()))
        m = types.MappingProxyType(d)
        self.assertEqual(pprint.pformat(m), """\
mappingproxy({'a': 6,
              'brown': 2,
              'dog': 8,
              'fox': 3,
              'jumped': 4,
              'lazy': 7,
              'over': 5,
              'quick': 1,
              'the': 0})""")
        d = collections.OrderedDict(zip(words, itertools.count()))
        m = types.MappingProxyType(d)
        self.assertEqual(pprint.pformat(m), """\
mappingproxy(OrderedDict([('the', 0),
                          ('quick', 1),
                          ('brown', 2),
                          ('fox', 3),
                          ('jumped', 4),
                          ('over', 5),
                          ('a', 6),
                          ('lazy', 7),
                          ('dog', 8)]))""") 
Example 63
Project: aws-lambda-runtime-pypy   Author: uscheller   File: headerregistry.py    Apache License 2.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example 64
Project: aws-lambda-runtime-pypy   Author: uscheller   File: enum.py    Apache License 2.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 65
Project: forge   Author: dfee   File: _signature.py    MIT License 5 votes vote down vote up
def parameters(self) -> types.MappingProxyType:
        """
        The signature's :class:`~forge.FParameter <parameters>`
        """
        return types.MappingProxyType(
            collections.OrderedDict([(p.name, p) for p in self._data])
        ) 
Example 66
Project: forge   Author: dfee   File: _utils.py    MIT License 5 votes vote down vote up
def __init__(
            self,
            *args: typing.Any,
            **kwargs: typing.Any
        ) -> None:
        super().__init__(args=args, kwargs=types.MappingProxyType(kwargs)) 
Example 67
Project: poker   Author: surgebiswas   File: __init__.py    MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example 68
Project: chekist   Author: JaneTurueva   File: main.py    MIT License 5 votes vote down vote up
def main():
    logging.basicConfig(level=logging.DEBUG)

    args = parser.parse_args()

    # Create file dirs
    if not os.path.isdir(args.files_dir):
        os.mkdir(args.files_dir)

    files_subdirs = ('photos', 'faces')
    for subdir in files_subdirs:
        subdir_path = os.path.join(args.files_dir, subdir)
        if not os.path.isdir(subdir_path):
            os.mkdir(subdir_path)

    # Start app
    app = Application()

    app.on_startup.append(partial(setup_amqp, amqp_url=args.amqp_url))
    app.on_startup.append(partial(setup_pg, pg_url=args.pg_url,
                                  pg_pool_min_size=args.pg_pool_min_size,
                                  pg_pool_max_size=args.pg_pool_max_size))

    for handler in HANDLERS:
        app.router.add_route('*', handler.URL_PATH, handler)
    app.router.add_static('/files', args.files_dir)

    # Register aiohttp payload handlers
    # Important: inherited classes should be registered before parents.
    PAYLOAD_REGISTRY.register(JsonPayload, (Mapping, MappingProxyType))

    web.run_app(app, host=args.host, port=args.port) 
Example 69
Project: chekist   Author: JaneTurueva   File: payloads.py    MIT License 5 votes vote down vote up
def convert_mapping_proxy_type(value: MappingProxyType):
    return dict(value.items()) 
Example 70
Project: Repobot   Author: Desgard   File: test_pretty.py    MIT License 4 votes vote down vote up
def test_mappingproxy():
    MP = types.MappingProxyType
    underlying_dict = {}
    mp_recursive = MP(underlying_dict)
    underlying_dict[2] = mp_recursive
    underlying_dict[3] = underlying_dict

    cases = [
        (MP({}), "mappingproxy({})"),
        (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
        (MP({k: k.upper() for k in string.ascii_lowercase}),
         "mappingproxy({'a': 'A',\n"
         "              'b': 'B',\n"
         "              'c': 'C',\n"
         "              'd': 'D',\n"
         "              'e': 'E',\n"
         "              'f': 'F',\n"
         "              'g': 'G',\n"
         "              'h': 'H',\n"
         "              'i': 'I',\n"
         "              'j': 'J',\n"
         "              'k': 'K',\n"
         "              'l': 'L',\n"
         "              'm': 'M',\n"
         "              'n': 'N',\n"
         "              'o': 'O',\n"
         "              'p': 'P',\n"
         "              'q': 'Q',\n"
         "              'r': 'R',\n"
         "              's': 'S',\n"
         "              't': 'T',\n"
         "              'u': 'U',\n"
         "              'v': 'V',\n"
         "              'w': 'W',\n"
         "              'x': 'X',\n"
         "              'y': 'Y',\n"
         "              'z': 'Z'})"),
        (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
        (underlying_dict,
         "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
    ]
    for obj, expected in cases:
        nt.assert_equal(pretty.pretty(obj), expected) 
Example 71
Project: dino   Author: thenetcircle   File: environ.py    Apache License 2.0 4 votes vote down vote up
def get_acl_config() -> Union[MappingProxyType, dict]:
    acl_paths = None
    if 'DINO_ACL' in os.environ:
        acl_paths = [os.environ['DINO_ACL']]

    acls, _ = find_config_acl(acl_paths)

    if acls is None or len(acls) == 0:
        return MappingProxyType({
            'room': dict(),
            'channel': dict(),
            'available': dict(),
        })

    check_acls = [
        ('channel', acls.get('channel', None)),
        ('room', acls.get('room', None))
    ]
    checked_acls = {
        'available': dict(),
        'room': dict(),
        'channel': dict()
    }

    AclConfigValidator.validate_acl_config(acls, check_acls)

    for acl_target, target_acls in check_acls:
        if target_acls is None or len(target_acls) == 0:
            continue
        for action in target_acls:
            if target_acls[action] is None:
                continue

            keys = set(target_acls[action]['acls'])

            if 'exclude' in target_acls[action]:
                excludes = target_acls[action]['exclude']
                for exclude in excludes:
                    keys.remove(exclude)

            if action not in checked_acls[acl_target]:
                checked_acls[acl_target][action] = list()
            for acl in keys:
                checked_acls[acl_target][action].append(acl)
    return acls 
Example 72
Project: dino   Author: thenetcircle   File: environ.py    Apache License 2.0 4 votes vote down vote up
def init_acl_validators(gn_env: GNEnvironment) -> None:
    if len(gn_env.config) == 0 or gn_env.config.get(ConfigKeys.TESTING, False):
        # assume we're testing
        return

    acl_config = gn_env.config.get(ConfigKeys.ACL)

    validators = acl_config['validation']
    for acl_type, validation_config in validators.items():
        validation_type = validation_config['type']

        if validation_type == 'str_in_csv':
            csv = None
            if 'value' in validation_config:
                csv = validation_config['value']

            if csv == '##db##':
                try:
                    csv = gn_env.db.get_acl_validation_value(acl_type, 'str_in_csv')
                except AclValueNotFoundException:
                    logger.warning(
                            'acl config specifies to get value from db but no value found for type '
                            '"%s" and method "str_in_csv", will check for default value' % acl_type)
                    if 'default' not in validation_config or len(validation_config['default'].strip()) == 0:
                        raise RuntimeError('no default value found for type "%s" and method "str_in_csv"' % acl_type)

                    csv = validation_config['default']

            validation_config['value'] = AclStrInCsvValidator(csv)

        elif validation_type == 'range':
            validation_config['value'] = AclRangeValidator()

        elif validation_type == 'disallow':
            validation_config['value'] = AclDisallowValidator()

        elif validation_type == 'samechannel':
            validation_config['value'] = AclSameChannelValidator()

        elif validation_type == 'custom':
            validation_config['value'] = AclPatternValidator()

        elif validation_type == 'sameroom':
            validation_config['value'] = AclSameRoomValidator()

        elif validation_type == 'is_admin':
            validation_config['value'] = AclIsAdminValidator()

        elif validation_type == 'is_room_owner':
            validation_config['value'] = AclIsRoomOwnerValidator()

        elif validation_type == 'is_super_user':
            validation_config['value'] = AclIsSuperUserValidator()

        else:
            raise RuntimeError('unknown validation type "%s"' % validation_type)

    gn_env.config.set(ConfigKeys.ACL, MappingProxyType(acl_config)) 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: inspect.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        """Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        """

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY
                kind_defaults = False

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    name = param.name

                    if kind < top_kind:
                        msg = (
                            'wrong parameter order: {} parameter before {} '
                            'parameter'
                        )
                        msg = msg.format(_get_paramkind_descr(top_kind),
                                         _get_paramkind_descr(kind))
                        raise ValueError(msg)
                    elif kind > top_kind:
                        kind_defaults = False
                        top_kind = kind

                    if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
                        if param.default is _empty:
                            if kind_defaults:
                                # No default for this parameter, but the
                                # previous parameter of the same kind had
                                # a default
                                msg = 'non-default argument follows default ' \
                                      'argument'
                                raise ValueError(msg)
                        else:
                            # There is a default for this parameter.
                            kind_defaults = True

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)

                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 74
Project: buzzard   Author: airware   File: _dataset.py    Apache License 2.0 4 votes vote down vote up
def acreate_cached_raster_recipe(
            self,

            # raster attributes
            fp, dtype, channel_count, channels_schema=None, sr=None,

            # callbacks running on pool
            compute_array=None, merge_arrays=buzzard.utils.concat_arrays,

            # filesystem
            cache_dir=None, ow=False,

            # primitives
            queue_data_per_primitive=MappingProxyType({}), convert_footprint_per_primitive=None,

            # pools
            computation_pool='cpu', merge_pool='cpu', io_pool='io', resample_pool='cpu',

            # misc
            cache_tiles=(512, 512), computation_tiles=None, max_resampling_size=None,
            debug_observers=()
    ):
        """Create a cached raster reciped anonymously within this Dataset.

        See Dataset.create_cached_raster_recipe

        See Also
        --------
        - :py:meth:`Dataset.create_raster_recipe`: To skip the `caching`
        - :py:meth:`Dataset.create_cached_raster_recipe`: To assign a `key` to this source within the `Dataset`

        """
        return self.create_cached_raster_recipe(
            _AnonymousSentry(),
            fp, dtype, channel_count, channels_schema, sr,
            compute_array, merge_arrays,
            cache_dir, ow,
            queue_data_per_primitive, convert_footprint_per_primitive,
            computation_pool, merge_pool, io_pool, resample_pool,
            cache_tiles, computation_tiles, max_resampling_size,
            debug_observers,
        )

    # Vector entry points *********************************************************************** ** 
Example 75
Project: unhuman-resources   Author: agajdosi   File: web_request.py    GNU General Public License v3.0 4 votes vote down vote up
def forwarded(self) -> Tuple[Mapping[str, str], ...]:
        """A tuple containing all parsed Forwarded header(s).

        Makes an effort to parse Forwarded headers as specified by RFC 7239:

        - It adds one (immutable) dictionary per Forwarded 'field-value', ie
          per proxy. The element corresponds to the data in the Forwarded
          field-value added by the first proxy encountered by the client. Each
          subsequent item corresponds to those added by later proxies.
        - It checks that every value has valid syntax in general as specified
          in section 4: either a 'token' or a 'quoted-string'.
        - It un-escapes found escape sequences.
        - It does NOT validate 'by' and 'for' contents as specified in section
          6.
        - It does NOT validate 'host' contents (Host ABNF).
        - It does NOT validate 'proto' contents for valid URI scheme names.

        Returns a tuple containing one or more immutable dicts
        """
        elems = []
        for field_value in self._message.headers.getall(hdrs.FORWARDED, ()):
            length = len(field_value)
            pos = 0
            need_separator = False
            elem = {}  # type: Dict[str, str]
            elems.append(types.MappingProxyType(elem))
            while 0 <= pos < length:
                match = _FORWARDED_PAIR_RE.match(field_value, pos)
                if match is not None:           # got a valid forwarded-pair
                    if need_separator:
                        # bad syntax here, skip to next comma
                        pos = field_value.find(',', pos)
                    else:
                        name, value, port = match.groups()
                        if value[0] == '"':
                            # quoted string: remove quotes and unescape
                            value = _QUOTED_PAIR_REPLACE_RE.sub(r'\1',
                                                                value[1:-1])
                        if port:
                            value += port
                        elem[name.lower()] = value
                        pos += len(match.group(0))
                        need_separator = True
                elif field_value[pos] == ',':      # next forwarded-element
                    need_separator = False
                    elem = {}
                    elems.append(types.MappingProxyType(elem))
                    pos += 1
                elif field_value[pos] == ';':      # next forwarded-pair
                    need_separator = False
                    pos += 1
                elif field_value[pos] in ' \t':
                    # Allow whitespace even between forwarded-pairs, though
                    # RFC 7239 doesn't. This simplifies code and is in line
                    # with Postel's law.
                    pos += 1
                else:
                    # bad syntax here, skip to next comma
                    pos = field_value.find(',', pos)
        return tuple(elems) 
Example 76
Project: Blockly-rduino-communication   Author: technologiescollege   File: inspect.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        '''Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        '''

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY
                kind_defaults = False

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    name = param.name

                    if kind < top_kind:
                        msg = 'wrong parameter order: {!r} before {!r}'
                        msg = msg.format(top_kind, kind)
                        raise ValueError(msg)
                    elif kind > top_kind:
                        kind_defaults = False
                        top_kind = kind

                    if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
                        if param.default is _empty:
                            if kind_defaults:
                                # No default for this parameter, but the
                                # previous parameter of the same kind had
                                # a default
                                msg = 'non-default argument follows default ' \
                                      'argument'
                                raise ValueError(msg)
                        else:
                            # There is a default for this parameter.
                            kind_defaults = True

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)

                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 77
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: inspect.py    GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        """Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        """

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY
                kind_defaults = False

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    name = param.name

                    if kind < top_kind:
                        msg = (
                            'wrong parameter order: {} parameter before {} '
                            'parameter'
                        )
                        msg = msg.format(_get_paramkind_descr(top_kind),
                                         _get_paramkind_descr(kind))
                        raise ValueError(msg)
                    elif kind > top_kind:
                        kind_defaults = False
                        top_kind = kind

                    if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
                        if param.default is _empty:
                            if kind_defaults:
                                # No default for this parameter, but the
                                # previous parameter of the same kind had
                                # a default
                                msg = 'non-default argument follows default ' \
                                      'argument'
                                raise ValueError(msg)
                        else:
                            # There is a default for this parameter.
                            kind_defaults = True

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)

                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 78
Project: aws-lambda-runtime-pypy   Author: uscheller   File: inspect.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        """Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        """

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY
                kind_defaults = False

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    name = param.name

                    if kind < top_kind:
                        msg = 'wrong parameter order: {!r} before {!r}'
                        msg = msg.format(top_kind, kind)
                        raise ValueError(msg)
                    elif kind > top_kind:
                        kind_defaults = False
                        top_kind = kind

                    if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
                        if param.default is _empty:
                            if kind_defaults:
                                # No default for this parameter, but the
                                # previous parameter of the same kind had
                                # a default
                                msg = 'non-default argument follows default ' \
                                      'argument'
                                raise ValueError(msg)
                        else:
                            # There is a default for this parameter.
                            kind_defaults = True

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)

                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 79
Project: forge   Author: dfee   File: _signature.py    MIT License 4 votes vote down vote up
def __init__(
            self,
            kind: _TYPE_FP_KIND,
            name: _TYPE_FP_NAME = None,
            interface_name: _TYPE_FP_NAME = None,
            default: _TYPE_FP_DEFAULT = empty,
            factory: _TYPE_FP_FACTORY = empty,
            type: _TYPE_FP_TYPE = empty,
            converter: _TYPE_FP_CONVERTER = None,
            validator: _TYPE_FP_VALIDATOR = None,
            bound: _TYPE_FP_BOUND = False,
            contextual: _TYPE_FP_CONTEXTUAL = False,
            metadata: typing.Optional[_TYPE_FP_METADATA] = None
        ) -> None:
        # pylint: disable=W0622, redefined-builtin
        # pylint: disable=R0913, too-many-arguments
        if name is not None and not isinstance(name, str):
            # Do enough validation of name to enable the Sequence functionality
            # of FSignature
            raise TypeError(
                'name must be a str, not a {}'.format(name),
            )

        if interface_name is not None and not isinstance(interface_name, str):
            raise TypeError(
                'interface_name must be a str, not a {}'.format(interface_name)
            )

        if factory is not empty:
            if default is not empty:
                raise TypeError(
                    'expected either "default" or "factory", received both'
                )
            default = Factory(factory)

        if bound and default is empty:
            raise TypeError('bound arguments must have a default value')

        super().__init__(
            kind=kind,
            name=name or interface_name,
            interface_name=interface_name or name,
            default=default,
            type=type,
            converter=converter,
            validator=validator,
            contextual=contextual,
            bound=bound,
            metadata=types.MappingProxyType(metadata or {}),
        ) 
Example 80
Project: freezedata   Author: topper-123   File: freezedata.py    MIT License 4 votes vote down vote up
def freeze_data(obj, *, allow=frozenset()):
    """Convert 'obj' recursively to a read-only object but selectively
    allow functions, modules and other hashables, which may not be read-only.
    This means that recursively:
    - ints, floats, strings, bytes, None and bools are kept unchanged
    - lists are converted to tuples
    - dicts are converted to types.MappingProxyType
    - sets are converted to frozensets
    - modules (if allowed) will unchanged. If root object s a module, it will be converted to
      a namedtuple
    - classes and instances (if allowed) are converted to namedtuples
    - namedtuples are created anew and values recursively made read-only

    If 'obj' is a function, a ValueError is raised, as functions are not read-only
    (e.g. the function's .__globals__ will be accessible). However, functions are often useful
    to retain in the data structures, so if string 'functions' is found in 'allow',
    functions are *copied* to new functions. The user of the data structure *will* be
    allowed access to the original function's .__globals__ attributes etc., so keep this in mind.

    class objects are also not necessarily read-only and will by default raise ValueErrors.
    However, if a string 'classes' is in 'allow', the class objects will be converted to
    namedtuple instances.

    class instances (beside from built-in immutables like 9, "er", 9.7 etc.) will raise
    ValueError by default. If a string 'instances' is set in 'allow', instances will
    be converted to namedtuple instances.

    If other objects than lists, sets, instances etc mentioned above are found, a ValueError
    will be raised.

    Notice: The created read-only objects is not hashable if the original object contains dicts, as
    types.MappingProxyType is not hashable.

    """

    allowed_ = {'functions', 'modules', 'classes', 'instances'}
    if isinstance(allow, (str)):
        allow = frozenset((allow,))
    elif not isinstance(allow, (set, frozenset)):
        allow = frozenset(allow)
    if not allow <= allowed_:
        raise ValueError("'allow' must be in %r" % (allowed_))

    if isinstance(obj, types.ModuleType):
        return freeze_class_or_istance_or_module(obj, allow=allow)
    else:
        return freeze_data_inner(obj, allow=allow)