Python typing.ChainMap() Examples

The following are 8 code examples of typing.ChainMap(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with 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 #2
Source File: dynamic_typing.py    From CrossHair with MIT License 5 votes vote down vote up
def unify_callable_args(value_types: Sequence[Type],
                        recv_types: Sequence[Type],
                        bindings: typing.ChainMap[object, Type]) -> bool:
    if value_types == ... or recv_types == ...:
        return True
    if len(value_types) != len(recv_types):
        return False
    for (varg, rarg) in zip(value_types, recv_types):
        # note reversal here: Callable is contravariant in argument types
        if not unify(rarg, varg, bindings):
            return False
    return True 
Example #3
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with 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 #4
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_chainmap_subclass(self):

        class MyChainMap(typing.ChainMap[str, int]):
            pass

        cm = MyChainMap()
        self.assertIsInstance(cm, MyChainMap)

        self.assertIsSubclass(MyChainMap, collections.ChainMap)
        self.assertNotIsSubclass(collections.ChainMap, MyChainMap) 
Example #5
Source File: schema.py    From lightbus with Apache License 2.0 5 votes vote down vote up
def load_local(self, source: Union[str, Path, TextIO] = None):
        """Load schemas from a local file

        These files will be treated as local schemas, and will not be sent to the bus.
        This can be useful for validation during development and testing.
        """
        if isinstance(source, str):
            source = Path(source)

        def _load_schema(path, file_data):
            try:
                return json.loads(file_data)
            except JSONDecodeError as e:
                raise InvalidSchema("Could not parse schema file {}: {}".format(path, e.msg))

        if source is None:
            # No source, read from stdin
            schema = _load_schema("[stdin]", sys.stdin.read())
        elif hasattr(source, "is_dir") and source.is_dir():
            # Read each json file in directory
            schemas = []
            for file_path in source.glob("*.json"):
                schemas.append(_load_schema(file_path, file_path.read_text(encoding="utf8")))
            schema = ChainMap(*schemas)
        elif hasattr(source, "read"):
            # Read file handle
            schema = _load_schema(source.name, source.read())
        elif hasattr(source, "read_text"):
            # Read pathlib Path
            schema = _load_schema(source.name, source.read_text())
        else:
            raise InvalidSchema(
                "Did not recognise provided source as either a "
                "directory path, file path, or file handle: {}".format(source)
            )

        for api_name, api_schema in schema.items():
            self.local_schemas[api_name] = api_schema

        return schema 
Example #6
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __new__(cls, *args, **kwds):
                if _geqv(cls, ChainMap):
                    return collections.ChainMap(*args, **kwds)
                return _generic_new(collections.ChainMap, cls, *args, **kwds) 
Example #7
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __new__(cls, *args, **kwds):
                if cls._gorg is ChainMap:
                    return collections.ChainMap(*args, **kwds)
                return _generic_new(collections.ChainMap, cls, *args, **kwds) 
Example #8
Source File: core.py    From CrossHair with MIT License 4 votes vote down vote up
def make_interceptor(self, original: Callable) -> Callable:
        subconditions = get_fn_conditions(original)
        if subconditions is None:
            return original
        sig = subconditions.sig

        def wrapper(*a: object, **kw: Dict[str, object]) -> object:
            #debug('short circuit wrapper ', original)
            if (not self.engaged) or self.space_getter().running_framework_code:
                return original(*a, **kw)
            # We *heavily* bias towards concrete execution, because it's often the case
            # that a single short-circuit will render the path useless. TODO: consider
            # decaying short-crcuit probability over time.
            use_short_circuit = self.space_getter().fork_with_confirm_or_else(0.95)
            if not use_short_circuit:
                debug('short circuit: Choosing not to intercept', original)
                return original(*a, **kw)
            try:
                self.engaged = False
                debug('short circuit: Intercepted a call to ', original)
                self.intercepted = True
                return_type = sig.return_annotation

                # Deduce type vars if necessary
                if len(typing_inspect.get_parameters(sig.return_annotation)) > 0 or typing_inspect.is_typevar(sig.return_annotation):
                    typevar_bindings: typing.ChainMap[object, type] = collections.ChainMap(
                    )
                    bound = sig.bind(*a, **kw)
                    bound.apply_defaults()
                    for param in sig.parameters.values():
                        argval = bound.arguments[param.name]
                        value_type = python_type(argval)
                        #debug('unify', value_type, param.annotation)
                        if not dynamic_typing.unify(value_type, param.annotation, typevar_bindings):
                            debug(
                                'aborting intercept due to signature unification failure')
                            return original(*a, **kw)
                        #debug('unify bindings', typevar_bindings)
                    return_type = dynamic_typing.realize(
                        sig.return_annotation, typevar_bindings)
                    debug('short circuit: Deduced return type was ', return_type)

                # adjust arguments that may have been mutated
                assert subconditions is not None
                bound = sig.bind(*a, **kw)
                mutable_args = subconditions.mutable_args
                for argname, arg in bound.arguments.items():
                    if mutable_args is None or argname in mutable_args:
                        forget_contents(arg, self.space_getter())

                if return_type is type(None):
                    return None
                # note that the enforcement wrapper ensures postconditions for us, so we
                # can just return a free variable here.
                return proxy_for_type(return_type, self.space_getter(), 'proxyreturn' + self.space_getter().uniq())
            finally:
                self.engaged = True
        functools.update_wrapper(wrapper, original)
        return wrapper