How to use the typing.Mapping function in typing

To help you get started, we’ve selected a few typing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lebrice / SimpleParsing / test / utils / View on Github external
"bob": {"name": "Bob", "age": 10},
                "clarice": {"name": "Clarice", "age": 10},
                "jeremy": None,
        assert ParentWithOptionalChildren.loads(nancy.dumps()) == nancy 

    class ChildWithFriends(Child):
        friends: List[Optional[Child]] = mutable_field(list)

    class ParentWithOptionalChildrenWithFriends(Serializable):
        name: str = "Consuela"
        children: Mapping[str, Optional[ChildWithFriends]] = mutable_field(OrderedDict)

    def test_lists(silent):
        bob = ChildWithFriends("Bob")
        clarice = Child("Clarice")

        nancy = ParentWithOptionalChildrenWithFriends("Nancy", children=dict(bob=bob))    
        nancy.children["jeremy"] = None

        assert nancy.to_dict() == {
            "name": "Nancy",
            "children": {
                "bob": {"name": "Bob", "age": 10, "friends": [
github python / typing / python2 / View on Github external
def test_weakref_all(self):
        T = TypeVar('T')
        things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any],
                  Optional[List[int]], typing.Mapping[int, str],
        [bytes], typing.Iterable['whatever']]
        for t in things:
            self.assertEqual(weakref.ref(t)(), t)
github edgedb / edgedb / edb / schema / View on Github external
def from_subtypes(
        cls: typing.Type[BaseTuple_T],
        schema: s_schema.Schema,
        subtypes: Union[Iterable[Type], Mapping[str, Type]],
        typemods: Any = None,
        name: Optional[s_name.Name] = None,
        id: Union[uuid.UUID, so.NoDefaultT] = so.NoDefault,
    ) -> BaseTuple_T:
        named = False
        if typemods is not None:
            named = typemods.get('named', False)

        types: Mapping[str, Type]
        if isinstance(subtypes,
            types = subtypes
            types = {str(i): type for i, type in enumerate(subtypes)}
        return cls.create(schema, element_types=types, named=named,
                          name=name, id=id, **kwargs)
github dotnet / performance / src / benchmarks / gc / src / analysis / View on Github external
return res

def _condemned_reason_group_of_bool_condemned_reason(
    b: BoolCondemnedReason
) -> _CondemnedReasonGroup:
    res = _CondemnedReasonGroup(enum_value(b) + enum_count(GenCondemnedReason))
    assert ==
    return res

class CondemnedReasonsForHeap:
    # Only has non-Gen0 entries
    gen_reasons: Mapping[GenCondemnedReason, Gens]
    bool_reasons: FrozenSet[BoolCondemnedReason]

    def is_empty(self) -> bool:
        return is_empty(self.gen_reasons) and is_empty(self.bool_reasons)

    def get_gen(self) -> Gens:
        return self.gen_reasons.get(GenCondemnedReason.final_generation, Gens.Gen0)

    def initial_generation(self) -> Optional[Gens]:
        return self.gen_reasons.get(GenCondemnedReason.initial_generation)

    def final_generation(self) -> Optional[Gens]:
        return self.gen_reasons[GenCondemnedReason.final_generation]
github asappresearch / flambe / flambe / experiment / View on Github external
def traverse_all(obj: Any) -> Iterable[Any]:
    """Iterate over all nested mappings and sequences

    obj: Any

        Iterable of child values to obj

    if isinstance(obj, Mapping):
        for key, value in obj.items():
            yield from traverse_all(value)
    elif isinstance(obj, Iterable) and not isinstance(obj, str):
        for value in obj:
            yield from traverse_all(value)
        yield obj
github eflglobal / filters / filters / View on Github external
def iter(self, value):
        # type: (Iterable) -> Generator[Any]
        Iterator version of :py:meth:`apply`.
        if value is not None:
            if isinstance(value, Mapping):
                for k, v in iteritems(value):
                    u_key = self.unicodify_key(k)

                    if (
                            (self.restrict_keys is None)
                        or  (k in self.restrict_keys)
                        yield k, self._apply_item(u_key, v, self._filter_chain)
                        # For consistency with FilterMapper, invalid
                        # keys are not included in the filtered
                        # value (hence this statement does not
                        # ``yield``).
                            value   = v,
                            reason  = self.CODE_EXTRA_KEY,
github todofixthis / class-registry / class_registry / View on Github external

class RegistryKeyError(KeyError):
    Used to differentiate a registry lookup from a standard KeyError.

    This is especially useful when a registry class expects to extract
    values from dicts to generate keys.

class BaseRegistry(typing.Mapping, metaclass=ABCMeta):
    Base functionality for registries.

    def __contains__(self, key):
        Returns whether the specified key is registered.
            # Use :py:meth:`get_class` instead of :py:meth:`__getitem__`
            # in case the registered class' initializer requires
            # arguments.
        except RegistryKeyError:
            return False
github thautwarm / Redy / Redy / Opt / View on Github external
self._feature = _

    def register(self, feature: 'Feature'):

    def setup_env(self, feature: 'Feature') -> None:

    def exit_env(self):

    def __call__(self, elem):
        return self.get_dispatch(elem)

class CompilingTimeContext(typing.Mapping):
    def __len__(self) -> int:
        raise NotImplemented

    def __iter__(self):
        raise NotImplemented

    def __init__(self, globals: dict, closure: dict):
        :param locals: a dictionary made from outside closure.
        self.locals = {}
        self.closure = closure
        self.globals = globals

    def __contains__(self, item):
        return item in self.closure or item in self.locals or item in self.globals
github StevenLooman / async_upnp_client / async_upnp_client / profiles / View on Github external
async def _fetch_headers(self, url: str, headers: Mapping[str, str]) \
            -> Optional[Mapping[str, str]]:
        """Do a HEAD/GET to get resources headers."""
        requester = self.device.requester

        # try a HEAD first
        status, headers, _ = await requester.async_http_request('HEAD',
        if 200 <= status < 300:
            return headers

        # then try a GET
        status, headers, _ = await requester.async_http_request('GET',
github facebookexperimental / buckit / fs_image / compiler / items / View on Github external
# something that another item `provides()`.
    # By having this phase be last, we also allow removing files added by
    # RPM_INSTALL.  The downside is that this is a footgun.  The upside is
    # that e.g.  cleaning up yum log & caches can be done as an
    # `image_feature` instead of being code.  We might also use this to
    # remove e.g.  unnecessary parts of excessively monolithic RPMs.

class LayerOpts(NamedTuple):
    artifacts_may_require_repo: bool
    build_appliance: str
    layer_target: str
    yum_from_snapshot: str
    target_to_path: Mapping[str, str]
    subvolumes_dir: str
    preserve_yum_cache: bool

class ImageItem(type):
    'A metaclass for the types of items that can be installed into images.'
    def __new__(metacls, classname, bases, dct):

        # Future: `deepfrozen` has a less clunky way of doing this
        def customize_fields(kwargs):
            fn = dct.get('customize_fields')
            if fn:
            return kwargs

        # Some items, like RPM actions, are not sorted by dependencies, but