typing_extensions-3.7.4.1/0000755000175000017500000000000013555566352015410 5ustar ivanivan00000000000000typing_extensions-3.7.4.1/src_py3/0000755000175000017500000000000013555566352016772 5ustar ivanivan00000000000000typing_extensions-3.7.4.1/src_py3/typing_extensions.py0000644000175000017500000022300013523611432023113 0ustar ivanivan00000000000000import abc import collections import contextlib import sys import typing import collections.abc as collections_abc import operator # These are used by Protocol implementation # We use internal typing helpers here, but this significantly reduces # code duplication. (Also this is only until Protocol is in typing.) from typing import Generic, Callable, TypeVar, Tuple # After PEP 560, internal typing API was substantially reworked. # This is especially important for Protocol class which uses internal APIs # quite extensivelly. PEP_560 = sys.version_info[:3] >= (3, 7, 0) if PEP_560: GenericMeta = TypingMeta = type else: from typing import GenericMeta, TypingMeta OLD_GENERICS = False try: from typing import _type_vars, _next_in_mro, _type_check except ImportError: OLD_GENERICS = True try: from typing import _subs_tree # noqa SUBS_TREE = True except ImportError: SUBS_TREE = False try: from typing import _tp_cache except ImportError: def _tp_cache(x): return x try: from typing import _TypingEllipsis, _TypingEmpty except ImportError: class _TypingEllipsis: pass class _TypingEmpty: pass # The two functions below are copies of typing internal helpers. # They are needed by _ProtocolMeta def _no_slots_copy(dct): dict_copy = dict(dct) if '__slots__' in dict_copy: for slot in dict_copy['__slots__']: dict_copy.pop(slot, None) return dict_copy def _check_generic(cls, parameters): if not cls.__parameters__: raise TypeError("%s is not a generic class" % repr(cls)) alen = len(parameters) elen = len(cls.__parameters__) if alen != elen: raise TypeError("Too %s parameters for %s; actual %s, expected %s" % ("many" if alen > elen else "few", repr(cls), alen, elen)) if hasattr(typing, '_generic_new'): _generic_new = typing._generic_new else: # Note: The '_generic_new(...)' function is used as a part of the # process of creating a generic type and was added to the typing module # as of Python 3.5.3. # # We've defined '_generic_new(...)' below to exactly match the behavior # implemented in older versions of 'typing' bundled with Python 3.5.0 to # 3.5.2. This helps eliminate redundancy when defining collection types # like 'Deque' later. # # See https://github.com/python/typing/pull/308 for more details -- in # particular, compare and contrast the definition of types like # 'typing.List' before and after the merge. def _generic_new(base_cls, cls, *args, **kwargs): return base_cls.__new__(cls, *args, **kwargs) # See https://github.com/python/typing/pull/439 if hasattr(typing, '_geqv'): from typing import _geqv _geqv_defined = True else: _geqv = None _geqv_defined = False if sys.version_info[:2] >= (3, 6): import _collections_abc _check_methods_in_mro = _collections_abc._check_methods else: def _check_methods_in_mro(C, *methods): mro = C.__mro__ for method in methods: for B in mro: if method in B.__dict__: if B.__dict__[method] is None: return NotImplemented break else: return NotImplemented return True # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. 'ClassVar', 'Final', 'Type', # ABCs (from collections.abc). # The following are added depending on presence # of their non-generic counterparts in stdlib: # 'Awaitable', # 'AsyncIterator', # 'AsyncIterable', # 'Coroutine', # 'AsyncGenerator', # 'AsyncContextManager', # 'ChainMap', # Concrete collection types. 'ContextManager', 'Counter', 'Deque', 'DefaultDict', 'TypedDict', # One-off things. 'final', 'IntVar', 'Literal', 'NewType', 'overload', 'Text', 'TYPE_CHECKING', ] # Annotated relies on substitution trees of pep 560. It will not work for # versions of typing older than 3.5.3 HAVE_ANNOTATED = PEP_560 or SUBS_TREE if PEP_560: __all__.append("get_type_hints") if HAVE_ANNOTATED: __all__.append("Annotated") # Protocols are hard to backport to the original version of typing 3.5.0 HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0) if HAVE_PROTOCOLS: __all__.extend(['Protocol', 'runtime', 'runtime_checkable']) # TODO if hasattr(typing, 'NoReturn'): NoReturn = typing.NoReturn elif hasattr(typing, '_FinalTypingBase'): class _NoReturn(typing._FinalTypingBase, _root=True): """Special type indicating functions that never return. Example:: from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') This type is invalid in other positions, e.g., ``List[NoReturn]`` will fail in static type checkers. """ __slots__ = () def __instancecheck__(self, obj): raise TypeError("NoReturn cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("NoReturn cannot be used with issubclass().") NoReturn = _NoReturn(_root=True) else: class _NoReturnMeta(typing.TypingMeta): """Metaclass for NoReturn""" def __new__(cls, name, bases, namespace, _root=False): return super().__new__(cls, name, bases, namespace, _root=_root) def __instancecheck__(self, obj): raise TypeError("NoReturn cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("NoReturn cannot be used with issubclass().") class NoReturn(typing.Final, metaclass=_NoReturnMeta, _root=True): """Special type indicating functions that never return. Example:: from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') This type is invalid in other positions, e.g., ``List[NoReturn]`` will fail in static type checkers. """ __slots__ = () # Some unconstrained type variables. These are used by the container types. # (These are not for export.) T = typing.TypeVar('T') # Any type. KT = typing.TypeVar('KT') # Key type. VT = typing.TypeVar('VT') # Value type. T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. V_co = typing.TypeVar('V_co', covariant=True) # Any type covariant containers. VT_co = typing.TypeVar('VT_co', covariant=True) # Value type covariant containers. T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. if hasattr(typing, 'ClassVar'): ClassVar = typing.ClassVar elif hasattr(typing, '_FinalTypingBase'): class _ClassVar(typing._FinalTypingBase, _root=True): """Special type construct to mark class variables. An annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:: class Starship: stats: ClassVar[Dict[str, int]] = {} # class variable damage: int = 10 # instance variable ClassVar accepts only types and cannot be further subscribed. Note that ClassVar is not a class itself, and should not be used with isinstance() or issubclass(). """ __slots__ = ('__type__',) def __init__(self, tp=None, **kwds): self.__type__ = tp def __getitem__(self, item): cls = type(self) if self.__type__ is None: return cls(typing._type_check(item, '{} accepts only single type.'.format(cls.__name__[1:])), _root=True) raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) def _eval_type(self, globalns, localns): new_tp = typing._eval_type(self.__type__, globalns, localns) if new_tp == self.__type__: return self return type(self)(new_tp, _root=True) def __repr__(self): r = super().__repr__() if self.__type__ is not None: r += '[{}]'.format(typing._type_repr(self.__type__)) return r def __hash__(self): return hash((type(self).__name__, self.__type__)) def __eq__(self, other): if not isinstance(other, _ClassVar): return NotImplemented if self.__type__ is not None: return self.__type__ == other.__type__ return self is other ClassVar = _ClassVar(_root=True) else: class _ClassVarMeta(typing.TypingMeta): """Metaclass for ClassVar""" def __new__(cls, name, bases, namespace, tp=None, _root=False): self = super().__new__(cls, name, bases, namespace, _root=_root) if tp is not None: self.__type__ = tp return self def __instancecheck__(self, obj): raise TypeError("ClassVar cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("ClassVar cannot be used with issubclass().") def __getitem__(self, item): cls = type(self) if self.__type__ is not None: raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) param = typing._type_check( item, '{} accepts only single type.'.format(cls.__name__[1:])) return cls(self.__name__, self.__bases__, dict(self.__dict__), tp=param, _root=True) def _eval_type(self, globalns, localns): new_tp = typing._eval_type(self.__type__, globalns, localns) if new_tp == self.__type__: return self return type(self)(self.__name__, self.__bases__, dict(self.__dict__), tp=self.__type__, _root=True) def __repr__(self): r = super().__repr__() if self.__type__ is not None: r += '[{}]'.format(typing._type_repr(self.__type__)) return r def __hash__(self): return hash((type(self).__name__, self.__type__)) def __eq__(self, other): if not isinstance(other, ClassVar): return NotImplemented if self.__type__ is not None: return self.__type__ == other.__type__ return self is other class ClassVar(typing.Final, metaclass=_ClassVarMeta, _root=True): """Special type construct to mark class variables. An annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:: class Starship: stats: ClassVar[Dict[str, int]] = {} # class variable damage: int = 10 # instance variable ClassVar accepts only types and cannot be further subscribed. Note that ClassVar is not a class itself, and should not be used with isinstance() or issubclass(). """ __type__ = None # On older versions of typing there is an internal class named "Final". if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): Final = typing.Final elif sys.version_info[:2] >= (3, 7): class _FinalForm(typing._SpecialForm, _root=True): def __repr__(self): return 'typing_extensions.' + self._name def __getitem__(self, parameters): item = typing._type_check(parameters, '{} accepts only single type'.format(self._name)) return _GenericAlias(self, (item,)) Final = _FinalForm('Final', doc="""A special typing construct to indicate that a name cannot be re-assigned or overridden in a subclass. For example: MAX_SIZE: Final = 9000 MAX_SIZE += 1 # Error reported by type checker class Connection: TIMEOUT: Final[int] = 10 class FastConnector(Connection): TIMEOUT = 1 # Error reported by type checker There is no runtime checking of these properties.""") elif hasattr(typing, '_FinalTypingBase'): class _Final(typing._FinalTypingBase, _root=True): """A special typing construct to indicate that a name cannot be re-assigned or overridden in a subclass. For example: MAX_SIZE: Final = 9000 MAX_SIZE += 1 # Error reported by type checker class Connection: TIMEOUT: Final[int] = 10 class FastConnector(Connection): TIMEOUT = 1 # Error reported by type checker There is no runtime checking of these properties. """ __slots__ = ('__type__',) def __init__(self, tp=None, **kwds): self.__type__ = tp def __getitem__(self, item): cls = type(self) if self.__type__ is None: return cls(typing._type_check(item, '{} accepts only single type.'.format(cls.__name__[1:])), _root=True) raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) def _eval_type(self, globalns, localns): new_tp = typing._eval_type(self.__type__, globalns, localns) if new_tp == self.__type__: return self return type(self)(new_tp, _root=True) def __repr__(self): r = super().__repr__() if self.__type__ is not None: r += '[{}]'.format(typing._type_repr(self.__type__)) return r def __hash__(self): return hash((type(self).__name__, self.__type__)) def __eq__(self, other): if not isinstance(other, _Final): return NotImplemented if self.__type__ is not None: return self.__type__ == other.__type__ return self is other Final = _Final(_root=True) else: class _FinalMeta(typing.TypingMeta): """Metaclass for Final""" def __new__(cls, name, bases, namespace, tp=None, _root=False): self = super().__new__(cls, name, bases, namespace, _root=_root) if tp is not None: self.__type__ = tp return self def __instancecheck__(self, obj): raise TypeError("Final cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Final cannot be used with issubclass().") def __getitem__(self, item): cls = type(self) if self.__type__ is not None: raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) param = typing._type_check( item, '{} accepts only single type.'.format(cls.__name__[1:])) return cls(self.__name__, self.__bases__, dict(self.__dict__), tp=param, _root=True) def _eval_type(self, globalns, localns): new_tp = typing._eval_type(self.__type__, globalns, localns) if new_tp == self.__type__: return self return type(self)(self.__name__, self.__bases__, dict(self.__dict__), tp=self.__type__, _root=True) def __repr__(self): r = super().__repr__() if self.__type__ is not None: r += '[{}]'.format(typing._type_repr(self.__type__)) return r def __hash__(self): return hash((type(self).__name__, self.__type__)) def __eq__(self, other): if not isinstance(other, Final): return NotImplemented if self.__type__ is not None: return self.__type__ == other.__type__ return self is other class Final(typing.Final, metaclass=_FinalMeta, _root=True): """A special typing construct to indicate that a name cannot be re-assigned or overridden in a subclass. For example: MAX_SIZE: Final = 9000 MAX_SIZE += 1 # Error reported by type checker class Connection: TIMEOUT: Final[int] = 10 class FastConnector(Connection): TIMEOUT = 1 # Error reported by type checker There is no runtime checking of these properties. """ __type__ = None if hasattr(typing, 'final'): final = typing.final else: def final(f): """This decorator can be used to indicate to type checkers that the decorated method cannot be overridden, and decorated class cannot be subclassed. For example: class Base: @final def done(self) -> None: ... class Sub(Base): def done(self) -> None: # Error reported by type checker ... @final class Leaf: ... class Other(Leaf): # Error reported by type checker ... There is no runtime checking of these properties. """ return f def IntVar(name): return TypeVar(name) if hasattr(typing, 'Literal'): Literal = typing.Literal elif sys.version_info[:2] >= (3, 7): class _LiteralForm(typing._SpecialForm, _root=True): def __repr__(self): return 'typing_extensions.' + self._name def __getitem__(self, parameters): return _GenericAlias(self, parameters) Literal = _LiteralForm('Literal', doc="""A type that can be used to indicate to type checkers that the corresponding value has a value literally equivalent to the provided parameter. For example: var: Literal[4] = 4 The type checker understands that 'var' is literally equal to the value 4 and no other value. Literal[...] cannot be subclassed. There is no runtime checking verifying that the parameter is actually a value instead of a type.""") elif hasattr(typing, '_FinalTypingBase'): class _Literal(typing._FinalTypingBase, _root=True): """A type that can be used to indicate to type checkers that the corresponding value has a value literally equivalent to the provided parameter. For example: var: Literal[4] = 4 The type checker understands that 'var' is literally equal to the value 4 and no other value. Literal[...] cannot be subclassed. There is no runtime checking verifying that the parameter is actually a value instead of a type. """ __slots__ = ('__values__',) def __init__(self, values=None, **kwds): self.__values__ = values def __getitem__(self, values): cls = type(self) if self.__values__ is None: if not isinstance(values, tuple): values = (values,) return cls(values, _root=True) raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) def _eval_type(self, globalns, localns): return self def __repr__(self): r = super().__repr__() if self.__values__ is not None: r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) return r def __hash__(self): return hash((type(self).__name__, self.__values__)) def __eq__(self, other): if not isinstance(other, _Literal): return NotImplemented if self.__values__ is not None: return self.__values__ == other.__values__ return self is other Literal = _Literal(_root=True) else: class _LiteralMeta(typing.TypingMeta): """Metaclass for Literal""" def __new__(cls, name, bases, namespace, values=None, _root=False): self = super().__new__(cls, name, bases, namespace, _root=_root) if values is not None: self.__values__ = values return self def __instancecheck__(self, obj): raise TypeError("Literal cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Literal cannot be used with issubclass().") def __getitem__(self, item): cls = type(self) if self.__values__ is not None: raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) if not isinstance(item, tuple): item = (item,) return cls(self.__name__, self.__bases__, dict(self.__dict__), values=item, _root=True) def _eval_type(self, globalns, localns): return self def __repr__(self): r = super().__repr__() if self.__values__ is not None: r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) return r def __hash__(self): return hash((type(self).__name__, self.__values__)) def __eq__(self, other): if not isinstance(other, Literal): return NotImplemented if self.__values__ is not None: return self.__values__ == other.__values__ return self is other class Literal(typing.Final, metaclass=_LiteralMeta, _root=True): """A type that can be used to indicate to type checkers that the corresponding value has a value literally equivalent to the provided parameter. For example: var: Literal[4] = 4 The type checker understands that 'var' is literally equal to the value 4 and no other value. Literal[...] cannot be subclassed. There is no runtime checking verifying that the parameter is actually a value instead of a type. """ __values__ = None def _overload_dummy(*args, **kwds): """Helper for @overload to raise when called.""" raise NotImplementedError( "You should not call an overloaded function. " "A series of @overload-decorated functions " "outside a stub module should always be followed " "by an implementation that is not @overload-ed.") def overload(func): """Decorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should *not* be decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): # implementation goes here """ return _overload_dummy # This is not a real generic class. Don't use outside annotations. if hasattr(typing, 'Type'): Type = typing.Type else: # Internal type variable used for Type[]. CT_co = typing.TypeVar('CT_co', covariant=True, bound=type) class Type(typing.Generic[CT_co], extra=type): """A special construct usable to annotate class objects. For example, suppose we have the following classes:: class User: ... # Abstract base for User classes class BasicUser(User): ... class ProUser(User): ... class TeamUser(User): ... And a function that takes a class argument that's a subclass of User and returns an instance of the corresponding class:: U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: user = user_class() # (Here we could write the user object to a database) return user joe = new_user(BasicUser) At this point the type checker knows that joe has type BasicUser. """ __slots__ = () # Various ABCs mimicking those in collections.abc. # A few are simply re-exported for completeness. def _define_guard(type_name): """ Returns True if the given type isn't defined in typing but is defined in collections_abc. Adds the type to __all__ if the collection is found in either typing or collection_abc. """ if hasattr(typing, type_name): __all__.append(type_name) globals()[type_name] = getattr(typing, type_name) return False elif hasattr(collections_abc, type_name): __all__.append(type_name) return True else: return False class _ExtensionsGenericMeta(GenericMeta): def __subclasscheck__(self, subclass): """This mimics a more modern GenericMeta.__subclasscheck__() logic (that does not have problems with recursion) to work around interactions between collections, typing, and typing_extensions on older versions of Python, see https://github.com/python/typing/issues/501. """ if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0): if self.__origin__ is not None: if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: raise TypeError("Parameterized generics cannot be used with class " "or instance checks") return False if not self.__extra__: return super().__subclasscheck__(subclass) res = self.__extra__.__subclasshook__(subclass) if res is not NotImplemented: return res if self.__extra__ in subclass.__mro__: return True for scls in self.__extra__.__subclasses__(): if isinstance(scls, GenericMeta): continue if issubclass(subclass, scls): return True return False if _define_guard('Awaitable'): class Awaitable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, extra=collections_abc.Awaitable): __slots__ = () if _define_guard('Coroutine'): class Coroutine(Awaitable[V_co], typing.Generic[T_co, T_contra, V_co], metaclass=_ExtensionsGenericMeta, extra=collections_abc.Coroutine): __slots__ = () if _define_guard('AsyncIterable'): class AsyncIterable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, extra=collections_abc.AsyncIterable): __slots__ = () if _define_guard('AsyncIterator'): class AsyncIterator(AsyncIterable[T_co], metaclass=_ExtensionsGenericMeta, extra=collections_abc.AsyncIterator): __slots__ = () if hasattr(typing, 'Deque'): Deque = typing.Deque elif _geqv_defined: class Deque(collections.deque, typing.MutableSequence[T], metaclass=_ExtensionsGenericMeta, extra=collections.deque): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, Deque): return collections.deque(*args, **kwds) return _generic_new(collections.deque, cls, *args, **kwds) else: class Deque(collections.deque, typing.MutableSequence[T], metaclass=_ExtensionsGenericMeta, extra=collections.deque): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Deque: return collections.deque(*args, **kwds) return _generic_new(collections.deque, cls, *args, **kwds) if hasattr(typing, 'ContextManager'): ContextManager = typing.ContextManager elif hasattr(contextlib, 'AbstractContextManager'): class ContextManager(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, extra=contextlib.AbstractContextManager): __slots__ = () else: class ContextManager(typing.Generic[T_co]): __slots__ = () def __enter__(self): return self @abc.abstractmethod def __exit__(self, exc_type, exc_value, traceback): return None @classmethod def __subclasshook__(cls, C): if cls is ContextManager: # In Python 3.6+, it is possible to set a method to None to # explicitly indicate that the class does not implement an ABC # (https://bugs.python.org/issue25958), but we do not support # that pattern here because this fallback class is only used # in Python 3.5 and earlier. if (any("__enter__" in B.__dict__ for B in C.__mro__) and any("__exit__" in B.__dict__ for B in C.__mro__)): return True return NotImplemented if hasattr(typing, 'AsyncContextManager'): AsyncContextManager = typing.AsyncContextManager __all__.append('AsyncContextManager') elif hasattr(contextlib, 'AbstractAsyncContextManager'): class AsyncContextManager(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, extra=contextlib.AbstractAsyncContextManager): __slots__ = () __all__.append('AsyncContextManager') elif sys.version_info[:2] >= (3, 5): exec(""" class AsyncContextManager(typing.Generic[T_co]): __slots__ = () async def __aenter__(self): return self @abc.abstractmethod async def __aexit__(self, exc_type, exc_value, traceback): return None @classmethod def __subclasshook__(cls, C): if cls is AsyncContextManager: return _check_methods_in_mro(C, "__aenter__", "__aexit__") return NotImplemented __all__.append('AsyncContextManager') """) if hasattr(typing, 'DefaultDict'): DefaultDict = typing.DefaultDict elif _geqv_defined: class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], metaclass=_ExtensionsGenericMeta, extra=collections.defaultdict): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, DefaultDict): return collections.defaultdict(*args, **kwds) return _generic_new(collections.defaultdict, cls, *args, **kwds) else: class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], metaclass=_ExtensionsGenericMeta, extra=collections.defaultdict): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is DefaultDict: return collections.defaultdict(*args, **kwds) return _generic_new(collections.defaultdict, cls, *args, **kwds) if hasattr(typing, 'Counter'): Counter = typing.Counter elif (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 1): assert _geqv_defined _TInt = typing.TypeVar('_TInt') class _CounterMeta(typing.GenericMeta): """Metaclass for Counter""" def __getitem__(self, item): return super().__getitem__((item, int)) class Counter(collections.Counter, typing.Dict[T, int], metaclass=_CounterMeta, extra=collections.Counter): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, Counter): return collections.Counter(*args, **kwds) return _generic_new(collections.Counter, cls, *args, **kwds) elif _geqv_defined: class Counter(collections.Counter, typing.Dict[T, int], metaclass=_ExtensionsGenericMeta, extra=collections.Counter): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, Counter): return collections.Counter(*args, **kwds) return _generic_new(collections.Counter, cls, *args, **kwds) else: class Counter(collections.Counter, typing.Dict[T, int], metaclass=_ExtensionsGenericMeta, extra=collections.Counter): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Counter: return collections.Counter(*args, **kwds) return _generic_new(collections.Counter, cls, *args, **kwds) if hasattr(typing, 'ChainMap'): ChainMap = typing.ChainMap __all__.append('ChainMap') elif hasattr(collections, 'ChainMap'): # ChainMap only exists in 3.3+ if _geqv_defined: class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], metaclass=_ExtensionsGenericMeta, extra=collections.ChainMap): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, ChainMap): return collections.ChainMap(*args, **kwds) return _generic_new(collections.ChainMap, cls, *args, **kwds) else: class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], metaclass=_ExtensionsGenericMeta, extra=collections.ChainMap): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is ChainMap: return collections.ChainMap(*args, **kwds) return _generic_new(collections.ChainMap, cls, *args, **kwds) __all__.append('ChainMap') if _define_guard('AsyncGenerator'): class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra], metaclass=_ExtensionsGenericMeta, extra=collections_abc.AsyncGenerator): __slots__ = () if hasattr(typing, 'NewType'): NewType = typing.NewType else: def NewType(name, tp): """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int """ def new_type(x): return x new_type.__name__ = name new_type.__supertype__ = tp return new_type if hasattr(typing, 'Text'): Text = typing.Text else: Text = str if hasattr(typing, 'TYPE_CHECKING'): TYPE_CHECKING = typing.TYPE_CHECKING else: # Constant that's True when type checking, but False here. TYPE_CHECKING = False def _gorg(cls): """This function exists for compatibility with old typing versions.""" assert isinstance(cls, GenericMeta) if hasattr(cls, '_gorg'): return cls._gorg while cls.__origin__ is not None: cls = cls.__origin__ return cls if OLD_GENERICS: def _next_in_mro(cls): # noqa """This function exists for compatibility with old typing versions.""" next_in_mro = object for i, c in enumerate(cls.__mro__[:-1]): if isinstance(c, GenericMeta) and _gorg(c) is Generic: next_in_mro = cls.__mro__[i + 1] return next_in_mro _PROTO_WHITELIST = ['Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator', 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'ContextManager', 'AsyncContextManager'] def _get_protocol_attrs(cls): attrs = set() for base in cls.__mro__[:-1]: # without object if base.__name__ in ('Protocol', 'Generic'): continue annotations = getattr(base, '__annotations__', {}) for attr in list(base.__dict__.keys()) + list(annotations.keys()): if (not attr.startswith('_abc_') and attr not in ( '__abstractmethods__', '__annotations__', '__weakref__', '_is_protocol', '_is_runtime_protocol', '__dict__', '__args__', '__slots__', '__next_in_mro__', '__parameters__', '__origin__', '__orig_bases__', '__extra__', '__tree_hash__', '__doc__', '__subclasshook__', '__init__', '__new__', '__module__', '_MutableMapping__marker', '_gorg')): attrs.add(attr) return attrs def _is_callable_members_only(cls): return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls)) if hasattr(typing, 'Protocol'): Protocol = typing.Protocol elif HAVE_PROTOCOLS and not PEP_560: class _ProtocolMeta(GenericMeta): """Internal metaclass for Protocol. This exists so Protocol classes can be generic without deriving from Generic. """ if not OLD_GENERICS: def __new__(cls, name, bases, namespace, tvars=None, args=None, origin=None, extra=None, orig_bases=None): # This is just a version copied from GenericMeta.__new__ that # includes "Protocol" special treatment. (Comments removed for brevity.) assert extra is None # Protocols should not have extra if tvars is not None: assert origin is not None assert all(isinstance(t, TypeVar) for t in tvars), tvars else: tvars = _type_vars(bases) gvars = None for base in bases: if base is Generic: raise TypeError("Cannot inherit from plain Generic") if (isinstance(base, GenericMeta) and base.__origin__ in (Generic, Protocol)): if gvars is not None: raise TypeError( "Cannot inherit from Generic[...] or" " Protocol[...] multiple times.") gvars = base.__parameters__ if gvars is None: gvars = tvars else: tvarset = set(tvars) gvarset = set(gvars) if not tvarset <= gvarset: raise TypeError( "Some type variables (%s) " "are not listed in %s[%s]" % (", ".join(str(t) for t in tvars if t not in gvarset), "Generic" if any(b.__origin__ is Generic for b in bases) else "Protocol", ", ".join(str(g) for g in gvars))) tvars = gvars initial_bases = bases if (extra is not None and type(extra) is abc.ABCMeta and extra not in bases): bases = (extra,) + bases bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases) if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): bases = tuple(b for b in bases if b is not Generic) namespace.update({'__origin__': origin, '__extra__': extra}) self = super(GenericMeta, cls).__new__(cls, name, bases, namespace, _root=True) super(GenericMeta, self).__setattr__('_gorg', self if not origin else _gorg(origin)) self.__parameters__ = tvars self.__args__ = tuple(... if a is _TypingEllipsis else () if a is _TypingEmpty else a for a in args) if args else None self.__next_in_mro__ = _next_in_mro(self) if orig_bases is None: self.__orig_bases__ = initial_bases elif origin is not None: self._abc_registry = origin._abc_registry self._abc_cache = origin._abc_cache if hasattr(self, '_subs_tree'): self.__tree_hash__ = (hash(self._subs_tree()) if origin else super(GenericMeta, self).__hash__()) return self def __init__(cls, *args, **kwargs): super().__init__(*args, **kwargs) if not cls.__dict__.get('_is_protocol', None): cls._is_protocol = any(b is Protocol or isinstance(b, _ProtocolMeta) and b.__origin__ is Protocol for b in cls.__bases__) if cls._is_protocol: for base in cls.__mro__[1:]: if not (base in (object, Generic) or base.__module__ == 'collections.abc' and base.__name__ in _PROTO_WHITELIST or isinstance(base, TypingMeta) and base._is_protocol or isinstance(base, GenericMeta) and base.__origin__ is Generic): raise TypeError('Protocols can only inherit from other' ' protocols, got %r' % base) def _no_init(self, *args, **kwargs): if type(self)._is_protocol: raise TypeError('Protocols cannot be instantiated') cls.__init__ = _no_init def _proto_hook(other): if not cls.__dict__.get('_is_protocol', None): return NotImplemented if not isinstance(other, type): # Same error as for issubclass(1, int) raise TypeError('issubclass() arg 1 must be a class') for attr in _get_protocol_attrs(cls): for base in other.__mro__: if attr in base.__dict__: if base.__dict__[attr] is None: return NotImplemented break annotations = getattr(base, '__annotations__', {}) if (isinstance(annotations, typing.Mapping) and attr in annotations and isinstance(other, _ProtocolMeta) and other._is_protocol): break else: return NotImplemented return True if '__subclasshook__' not in cls.__dict__: cls.__subclasshook__ = _proto_hook def __instancecheck__(self, instance): # We need this method for situations where attributes are # assigned in __init__. if ((not getattr(self, '_is_protocol', False) or _is_callable_members_only(self)) and issubclass(instance.__class__, self)): return True if self._is_protocol: if all(hasattr(instance, attr) and (not callable(getattr(self, attr, None)) or getattr(instance, attr) is not None) for attr in _get_protocol_attrs(self)): return True return super(GenericMeta, self).__instancecheck__(instance) def __subclasscheck__(self, cls): if self.__origin__ is not None: if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: raise TypeError("Parameterized generics cannot be used with class " "or instance checks") return False if (self.__dict__.get('_is_protocol', None) and not self.__dict__.get('_is_runtime_protocol', None)): if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools', 'typing']: return False raise TypeError("Instance and class checks can only be used with" " @runtime protocols") if (self.__dict__.get('_is_runtime_protocol', None) and not _is_callable_members_only(self)): if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools', 'typing']: return super(GenericMeta, self).__subclasscheck__(cls) raise TypeError("Protocols with non-method members" " don't support issubclass()") return super(GenericMeta, self).__subclasscheck__(cls) if not OLD_GENERICS: @_tp_cache def __getitem__(self, params): # We also need to copy this from GenericMeta.__getitem__ to get # special treatment of "Protocol". (Comments removed for brevity.) if not isinstance(params, tuple): params = (params,) if not params and _gorg(self) is not Tuple: raise TypeError( "Parameter list to %s[...] cannot be empty" % self.__qualname__) msg = "Parameters to generic types must be types." params = tuple(_type_check(p, msg) for p in params) if self in (Generic, Protocol): if not all(isinstance(p, TypeVar) for p in params): raise TypeError( "Parameters to %r[...] must all be type variables" % self) if len(set(params)) != len(params): raise TypeError( "Parameters to %r[...] must all be unique" % self) tvars = params args = params elif self in (Tuple, Callable): tvars = _type_vars(params) args = params elif self.__origin__ in (Generic, Protocol): raise TypeError("Cannot subscript already-subscripted %s" % repr(self)) else: _check_generic(self, params) tvars = _type_vars(params) args = params prepend = (self,) if self.__origin__ is None else () return self.__class__(self.__name__, prepend + self.__bases__, _no_slots_copy(self.__dict__), tvars=tvars, args=args, origin=self, extra=self.__extra__, orig_bases=self.__orig_bases__) class Protocol(metaclass=_ProtocolMeta): """Base class for protocol classes. Protocol classes are defined as:: class Proto(Protocol): def meth(self) -> int: ... Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:: class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check See PEP 544 for details. Protocol classes decorated with @typing_extensions.runtime act as simple-minded runtime protocol that checks only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:: class GenProto({bases}): def meth(self) -> T: ... """ __slots__ = () _is_protocol = True def __new__(cls, *args, **kwds): if _gorg(cls) is Protocol: raise TypeError("Type Protocol cannot be instantiated; " "it can be used only as a base class") if OLD_GENERICS: return _generic_new(_next_in_mro(cls), cls, *args, **kwds) return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) if Protocol.__doc__ is not None: Protocol.__doc__ = Protocol.__doc__.format(bases="Protocol, Generic[T]" if OLD_GENERICS else "Protocol[T]") elif PEP_560: from typing import _type_check, _GenericAlias, _collect_type_vars # noqa class _ProtocolMeta(abc.ABCMeta): # This metaclass is a bit unfortunate and exists only because of the lack # of __instancehook__. def __instancecheck__(cls, instance): # We need this method for situations where attributes are # assigned in __init__. if ((not getattr(cls, '_is_protocol', False) or _is_callable_members_only(cls)) and issubclass(instance.__class__, cls)): return True if cls._is_protocol: if all(hasattr(instance, attr) and (not callable(getattr(cls, attr, None)) or getattr(instance, attr) is not None) for attr in _get_protocol_attrs(cls)): return True return super().__instancecheck__(instance) class Protocol(metaclass=_ProtocolMeta): # There is quite a lot of overlapping code with typing.Generic. # Unfortunately it is hard to avoid this while these live in two different # modules. The duplicated code will be removed when Protocol is moved to typing. """Base class for protocol classes. Protocol classes are defined as:: class Proto(Protocol): def meth(self) -> int: ... Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:: class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check See PEP 544 for details. Protocol classes decorated with @typing_extensions.runtime act as simple-minded runtime protocol that checks only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:: class GenProto(Protocol[T]): def meth(self) -> T: ... """ __slots__ = () _is_protocol = True def __new__(cls, *args, **kwds): if cls is Protocol: raise TypeError("Type Protocol cannot be instantiated; " "it can only be used as a base class") return super().__new__(cls) @_tp_cache def __class_getitem__(cls, params): if not isinstance(params, tuple): params = (params,) if not params and cls is not Tuple: raise TypeError( "Parameter list to {}[...] cannot be empty".format(cls.__qualname__)) msg = "Parameters to generic types must be types." params = tuple(_type_check(p, msg) for p in params) if cls is Protocol: # Generic can only be subscripted with unique type variables. if not all(isinstance(p, TypeVar) for p in params): i = 0 while isinstance(params[i], TypeVar): i += 1 raise TypeError( "Parameters to Protocol[...] must all be type variables." " Parameter {} is {}".format(i + 1, params[i])) if len(set(params)) != len(params): raise TypeError( "Parameters to Protocol[...] must all be unique") else: # Subscripting a regular Generic subclass. _check_generic(cls, params) return _GenericAlias(cls, params) def __init_subclass__(cls, *args, **kwargs): tvars = [] if '__orig_bases__' in cls.__dict__: error = Generic in cls.__orig_bases__ else: error = Generic in cls.__bases__ if error: raise TypeError("Cannot inherit from plain Generic") if '__orig_bases__' in cls.__dict__: tvars = _collect_type_vars(cls.__orig_bases__) # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn]. # If found, tvars must be a subset of it. # If not found, tvars is it. # Also check for and reject plain Generic, # and reject multiple Generic[...] and/or Protocol[...]. gvars = None for base in cls.__orig_bases__: if (isinstance(base, _GenericAlias) and base.__origin__ in (Generic, Protocol)): # for error messages the_base = 'Generic' if base.__origin__ is Generic else 'Protocol' if gvars is not None: raise TypeError( "Cannot inherit from Generic[...]" " and/or Protocol[...] multiple types.") gvars = base.__parameters__ if gvars is None: gvars = tvars else: tvarset = set(tvars) gvarset = set(gvars) if not tvarset <= gvarset: s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) s_args = ', '.join(str(g) for g in gvars) raise TypeError("Some type variables ({}) are" " not listed in {}[{}]".format(s_vars, the_base, s_args)) tvars = gvars cls.__parameters__ = tuple(tvars) # Determine if this is a protocol or a concrete subclass. if not cls.__dict__.get('_is_protocol', None): cls._is_protocol = any(b is Protocol for b in cls.__bases__) # Set (or override) the protocol subclass hook. def _proto_hook(other): if not cls.__dict__.get('_is_protocol', None): return NotImplemented if not getattr(cls, '_is_runtime_protocol', False): if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: return NotImplemented raise TypeError("Instance and class checks can only be used with" " @runtime protocols") if not _is_callable_members_only(cls): if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: return NotImplemented raise TypeError("Protocols with non-method members" " don't support issubclass()") if not isinstance(other, type): # Same error as for issubclass(1, int) raise TypeError('issubclass() arg 1 must be a class') for attr in _get_protocol_attrs(cls): for base in other.__mro__: if attr in base.__dict__: if base.__dict__[attr] is None: return NotImplemented break annotations = getattr(base, '__annotations__', {}) if (isinstance(annotations, typing.Mapping) and attr in annotations and isinstance(other, _ProtocolMeta) and other._is_protocol): break else: return NotImplemented return True if '__subclasshook__' not in cls.__dict__: cls.__subclasshook__ = _proto_hook # We have nothing more to do for non-protocols. if not cls._is_protocol: return # Check consistency of bases. for base in cls.__bases__: if not (base in (object, Generic) or base.__module__ == 'collections.abc' and base.__name__ in _PROTO_WHITELIST or isinstance(base, _ProtocolMeta) and base._is_protocol): raise TypeError('Protocols can only inherit from other' ' protocols, got %r' % base) def _no_init(self, *args, **kwargs): if type(self)._is_protocol: raise TypeError('Protocols cannot be instantiated') cls.__init__ = _no_init if hasattr(typing, 'runtime_checkable'): runtime_checkable = typing.runtime_checkable elif HAVE_PROTOCOLS: def runtime_checkable(cls): """Mark a protocol class as a runtime protocol, so that it can be used with isinstance() and issubclass(). Raise TypeError if applied to a non-protocol class. This allows a simple-minded structural check very similar to the one-offs in collections.abc such as Hashable. """ if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol: raise TypeError('@runtime_checkable can be only applied to protocol classes,' ' got %r' % cls) cls._is_runtime_protocol = True return cls if HAVE_PROTOCOLS: # Exists for backwards compatibility. runtime = runtime_checkable if hasattr(typing, 'TypedDict'): TypedDict = typing.TypedDict else: def _check_fails(cls, other): try: if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']: # Typed dicts are only for static structural subtyping. raise TypeError('TypedDict does not support instance and class checks') except (AttributeError, ValueError): pass return False def _dict_new(cls, *args, **kwargs): return dict(*args, **kwargs) def _typeddict_new(cls, _typename, _fields=None, **kwargs): total = kwargs.pop('total', True) if _fields is None: _fields = kwargs elif kwargs: raise TypeError("TypedDict takes either a dict or keyword arguments," " but not both") ns = {'__annotations__': dict(_fields), '__total__': total} try: # Setting correct module is necessary to make typed dict classes pickleable. ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass return _TypedDictMeta(_typename, (), ns) class _TypedDictMeta(type): def __new__(cls, name, bases, ns, total=True): # Create new typed dict class object. # This method is called directly when TypedDict is subclassed, # or via _typeddict_new when TypedDict is instantiated. This way # TypedDict supports all three syntaxes described in its docstring. # Subclasses and instances of TypedDict return actual dictionaries # via _dict_new. ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns) anns = ns.get('__annotations__', {}) msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" anns = {n: typing._type_check(tp, msg) for n, tp in anns.items()} for base in bases: anns.update(base.__dict__.get('__annotations__', {})) tp_dict.__annotations__ = anns if not hasattr(tp_dict, '__total__'): tp_dict.__total__ = total return tp_dict __instancecheck__ = __subclasscheck__ = _check_fails TypedDict = _TypedDictMeta('TypedDict', (dict,), {}) TypedDict.__module__ = __name__ TypedDict.__doc__ = \ """A simple typed name space. At runtime it is equivalent to a plain dict. TypedDict creates a dictionary type that expects all of its instances to have a certain set of keys, with each key associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:: class Point2D(TypedDict): x: int y: int label: str a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') The type info could be accessed via Point2D.__annotations__. TypedDict supports two additional equivalent forms:: Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) The class syntax is only supported in Python 3.6+, while two other syntax forms work for Python 2.7 and 3.2+ """ if PEP_560: class _AnnotatedAlias(typing._GenericAlias, _root=True): """Runtime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra annotations. The alias behaves like a normal typing alias, instantiating is the same as instantiating the underlying type, binding it to types is also the same. """ def __init__(self, origin, metadata): if isinstance(origin, _AnnotatedAlias): metadata = origin.__metadata__ + metadata origin = origin.__origin__ super().__init__(origin, origin) self.__metadata__ = metadata def copy_with(self, params): assert len(params) == 1 new_type = params[0] return _AnnotatedAlias(new_type, self.__metadata__) def __repr__(self): return "typing_extensions.Annotated[{}, {}]".format( typing._type_repr(self.__origin__), ", ".join(repr(a) for a in self.__metadata__) ) def __reduce__(self): return operator.getitem, ( Annotated, (self.__origin__,) + self.__metadata__ ) def __eq__(self, other): if not isinstance(other, _AnnotatedAlias): return NotImplemented if self.__origin__ != other.__origin__: return False return self.__metadata__ == other.__metadata__ def __hash__(self): return hash((self.__origin__, self.__metadata__)) class Annotated: """Add context specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type (and will be in the __origin__ field), the remaining arguments are kept as a tuple in the __extra__ field. Details: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()] """ __slots__ = () def __new__(cls, *args, **kwargs): raise TypeError("Type Annotated cannot be instantiated.") @_tp_cache def __class_getitem__(cls, params): if not isinstance(params, tuple) or len(params) < 2: raise TypeError("Annotated[...] should be used " "with at least two arguments (a type and an " "annotation).") msg = "Annotated[t, ...]: t must be a type." origin = typing._type_check(params[0], msg) metadata = tuple(params[1:]) return _AnnotatedAlias(origin, metadata) def __init_subclass__(cls, *args, **kwargs): raise TypeError( "Cannot subclass {}.Annotated".format(cls.__module__) ) def _strip_annotations(t): """Strips the annotations from a given type. """ if isinstance(t, _AnnotatedAlias): return _strip_annotations(t.__origin__) if isinstance(t, typing._GenericAlias): stripped_args = tuple(_strip_annotations(a) for a in t.__args__) if stripped_args == t.__args__: return t res = t.copy_with(stripped_args) res._special = t._special return res return t def get_type_hints(obj, globalns=None, localns=None, include_extras=False): """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, adds Optional[t] if a default value equal to None is set and recursively replaces all 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members. TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present. BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals. - If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module's globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. - If one dict argument is passed, it is used for both globals and locals. - If two dict arguments are passed, they specify globals and locals, respectively. """ hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) if include_extras: return hint return {k: _strip_annotations(t) for k, t in hint.items()} elif HAVE_ANNOTATED: def _is_dunder(name): """Returns True if name is a __dunder_variable_name__.""" return len(name) > 4 and name.startswith('__') and name.endswith('__') # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality # checks, argument expansion etc. are done on the _subs_tre. As a result we # can't provide a get_type_hints function that strips out annotations. class AnnotatedMeta(typing.GenericMeta): """Metaclass for Annotated""" def __new__(cls, name, bases, namespace, **kwargs): if any(b is not object for b in bases): raise TypeError("Cannot subclass " + str(Annotated)) return super().__new__(cls, name, bases, namespace, **kwargs) @property def __metadata__(self): return self._subs_tree()[2] def _tree_repr(self, tree): cls, origin, metadata = tree if not isinstance(origin, tuple): tp_repr = typing._type_repr(origin) else: tp_repr = origin[0]._tree_repr(origin) metadata_reprs = ", ".join(repr(arg) for arg in metadata) return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs) def _subs_tree(self, tvars=None, args=None): # noqa if self is Annotated: return Annotated res = super()._subs_tree(tvars=tvars, args=args) # Flatten nested Annotated if isinstance(res[1], tuple) and res[1][0] is Annotated: sub_tp = res[1][1] sub_annot = res[1][2] return (Annotated, sub_tp, sub_annot + res[2]) return res def _get_cons(self): """Return the class used to create instance of this type.""" if self.__origin__ is None: raise TypeError("Cannot get the underlying type of a " "non-specialized Annotated type.") tree = self._subs_tree() while isinstance(tree, tuple) and tree[0] is Annotated: tree = tree[1] if isinstance(tree, tuple): return tree[0] else: return tree @_tp_cache def __getitem__(self, params): if not isinstance(params, tuple): params = (params,) if self.__origin__ is not None: # specializing an instantiated type return super().__getitem__(params) elif not isinstance(params, tuple) or len(params) < 2: raise TypeError("Annotated[...] should be instantiated " "with at least two arguments (a type and an " "annotation).") else: msg = "Annotated[t, ...]: t must be a type." tp = typing._type_check(params[0], msg) metadata = tuple(params[1:]) return self.__class__( self.__name__, self.__bases__, _no_slots_copy(self.__dict__), tvars=_type_vars((tp,)), # Metadata is a tuple so it won't be touched by _replace_args et al. args=(tp, metadata), origin=self, ) def __call__(self, *args, **kwargs): cons = self._get_cons() result = cons(*args, **kwargs) try: result.__orig_class__ = self except AttributeError: pass return result def __getattr__(self, attr): # For simplicity we just don't relay all dunder names if self.__origin__ is not None and not _is_dunder(attr): return getattr(self._get_cons(), attr) raise AttributeError(attr) def __setattr__(self, attr, value): if _is_dunder(attr) or attr.startswith('_abc_'): super().__setattr__(attr, value) elif self.__origin__ is None: raise AttributeError(attr) else: setattr(self._get_cons(), attr, value) def __instancecheck__(self, obj): raise TypeError("Annotated cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Annotated cannot be used with issubclass().") class Annotated(metaclass=AnnotatedMeta): """Add context specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type, the remaining arguments are kept as a tuple in the __metadata__ field. Details: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()] """ typing_extensions-3.7.4.1/src_py3/test_typing_extensions.py0000644000175000017500000016760513523611432024174 0ustar ivanivan00000000000000import sys import os import abc import contextlib import collections import pickle import subprocess import types from unittest import TestCase, main, skipUnless from typing import TypeVar, Optional from typing import T, KT, VT # Not in __all__. from typing import Tuple, List, Dict, Iterator from typing import Generic from typing import no_type_check from typing_extensions import NoReturn, ClassVar, Final, IntVar, Literal, Type, NewType, TypedDict try: from typing_extensions import Protocol, runtime, runtime_checkable except ImportError: pass try: from typing_extensions import Annotated except ImportError: pass try: from typing_extensions import get_type_hints except ImportError: from typing import get_type_hints import typing import typing_extensions import collections.abc as collections_abc PEP_560 = sys.version_info[:3] >= (3, 7, 0) OLD_GENERICS = False try: from typing import _type_vars, _next_in_mro, _type_check # noqa except ImportError: OLD_GENERICS = True # We assume Python versions *below* 3.5.0 will have the most # up-to-date version of the typing module installed. Since # the typing module isn't a part of the standard library in older # versions of Python, those users are likely to have a reasonably # modern version of `typing` installed from PyPi. TYPING_LATEST = sys.version_info[:3] < (3, 5, 0) # Flags used to mark tests that only apply after a specific # version of the typing module. TYPING_3_5_1 = TYPING_LATEST or sys.version_info[:3] >= (3, 5, 1) TYPING_3_5_3 = TYPING_LATEST or sys.version_info[:3] >= (3, 5, 3) TYPING_3_6_1 = TYPING_LATEST or sys.version_info[:3] >= (3, 6, 1) # For typing versions where issubclass(...) and # isinstance(...) checks are forbidden. # # See https://github.com/python/typing/issues/136 # and https://github.com/python/typing/pull/283 SUBCLASS_CHECK_FORBIDDEN = TYPING_3_5_3 # For typing versions where instantiating collection # types are allowed. # # See https://github.com/python/typing/issues/367 CAN_INSTANTIATE_COLLECTIONS = TYPING_3_6_1 # For Python versions supporting async/await and friends. ASYNCIO = sys.version_info[:2] >= (3, 5) # For checks reliant on Python 3.6 syntax changes (e.g. classvar) PY36 = sys.version_info[:2] >= (3, 6) # Protocols are hard to backport to the original version of typing 3.5.0 HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0) class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): message = '%r is not a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): if issubclass(cls, class_or_tuple): message = '%r is a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) class Employee: pass class NoReturnTests(BaseTestCase): def test_noreturn_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, NoReturn) def test_noreturn_subclass_type_error_1(self): with self.assertRaises(TypeError): issubclass(Employee, NoReturn) @skipUnless(SUBCLASS_CHECK_FORBIDDEN, "Behavior added in typing 3.5.3") def test_noreturn_subclass_type_error_2(self): with self.assertRaises(TypeError): issubclass(NoReturn, Employee) def test_repr(self): if hasattr(typing, 'NoReturn'): self.assertEqual(repr(NoReturn), 'typing.NoReturn') else: self.assertEqual(repr(NoReturn), 'typing_extensions.NoReturn') def test_not_generic(self): with self.assertRaises(TypeError): NoReturn[int] def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(NoReturn): pass if SUBCLASS_CHECK_FORBIDDEN: with self.assertRaises(TypeError): class A(type(NoReturn)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): NoReturn() with self.assertRaises(TypeError): type(NoReturn)() class ClassVarTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): ClassVar[1] with self.assertRaises(TypeError): ClassVar[int, str] with self.assertRaises(TypeError): ClassVar[int][str] def test_repr(self): if hasattr(typing, 'ClassVar'): mod_name = 'typing' else: mod_name = 'typing_extensions' self.assertEqual(repr(ClassVar), mod_name + '.ClassVar') cv = ClassVar[int] self.assertEqual(repr(cv), mod_name + '.ClassVar[int]') cv = ClassVar[Employee] self.assertEqual(repr(cv), mod_name + '.ClassVar[%s.Employee]' % __name__) @skipUnless(SUBCLASS_CHECK_FORBIDDEN, "Behavior added in typing 3.5.3") def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(ClassVar)): pass with self.assertRaises(TypeError): class C(type(ClassVar[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): ClassVar() with self.assertRaises(TypeError): type(ClassVar)() with self.assertRaises(TypeError): type(ClassVar[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, ClassVar[int]) with self.assertRaises(TypeError): issubclass(int, ClassVar) class FinalTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): Final[1] with self.assertRaises(TypeError): Final[int, str] with self.assertRaises(TypeError): Final[int][str] def test_repr(self): if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): mod_name = 'typing' else: mod_name = 'typing_extensions' self.assertEqual(repr(Final), mod_name + '.Final') cv = Final[int] self.assertEqual(repr(cv), mod_name + '.Final[int]') cv = Final[Employee] self.assertEqual(repr(cv), mod_name + '.Final[%s.Employee]' % __name__) @skipUnless(SUBCLASS_CHECK_FORBIDDEN, "Behavior added in typing 3.5.3") def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(Final)): pass with self.assertRaises(TypeError): class C(type(Final[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): Final() with self.assertRaises(TypeError): type(Final)() with self.assertRaises(TypeError): type(Final[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, Final[int]) with self.assertRaises(TypeError): issubclass(int, Final) class IntVarTests(BaseTestCase): def test_valid(self): T_ints = IntVar("T_ints") # noqa def test_invalid(self): with self.assertRaises(TypeError): T_ints = IntVar("T_ints", int) with self.assertRaises(TypeError): T_ints = IntVar("T_ints", bound=int) with self.assertRaises(TypeError): T_ints = IntVar("T_ints", covariant=True) # noqa class LiteralTests(BaseTestCase): def test_basics(self): Literal[1] Literal[1, 2, 3] Literal["x", "y", "z"] Literal[None] def test_illegal_parameters_do_not_raise_runtime_errors(self): # Type checkers should reject these types, but we do not # raise errors at runtime to maintain maximum flexibility Literal[int] Literal[Literal[1, 2], Literal[4, 5]] Literal[3j + 2, ..., ()] Literal[b"foo", u"bar"] Literal[{"foo": 3, "bar": 4}] Literal[T] def test_literals_inside_other_types(self): List[Literal[1, 2, 3]] List[Literal[("foo", "bar", "baz")]] def test_repr(self): if hasattr(typing, 'Literal'): mod_name = 'typing' else: mod_name = 'typing_extensions' self.assertEqual(repr(Literal[1]), mod_name + ".Literal[1]") self.assertEqual(repr(Literal[1, True, "foo"]), mod_name + ".Literal[1, True, 'foo']") self.assertEqual(repr(Literal[int]), mod_name + ".Literal[int]") self.assertEqual(repr(Literal), mod_name + ".Literal") self.assertEqual(repr(Literal[None]), mod_name + ".Literal[None]") def test_cannot_init(self): with self.assertRaises(TypeError): Literal() with self.assertRaises(TypeError): Literal[1]() with self.assertRaises(TypeError): type(Literal)() with self.assertRaises(TypeError): type(Literal[1])() def test_no_isinstance_or_issubclass(self): with self.assertRaises(TypeError): isinstance(1, Literal[1]) with self.assertRaises(TypeError): isinstance(int, Literal[1]) with self.assertRaises(TypeError): issubclass(1, Literal[1]) with self.assertRaises(TypeError): issubclass(int, Literal[1]) def test_no_subclassing(self): with self.assertRaises(TypeError): class Foo(Literal[1]): pass with self.assertRaises(TypeError): class Bar(Literal): pass def test_no_multiple_subscripts(self): with self.assertRaises(TypeError): Literal[1][1] class OverloadTests(BaseTestCase): def test_overload_fails(self): from typing_extensions import overload with self.assertRaises(RuntimeError): @overload def blah(): pass blah() def test_overload_succeeds(self): from typing_extensions import overload @overload def blah(): pass def blah(): pass blah() ASYNCIO_TESTS = """ import asyncio from typing import Iterable from typing_extensions import Awaitable, AsyncIterator T_a = TypeVar('T_a') class AwaitableWrapper(Awaitable[T_a]): def __init__(self, value): self.value = value def __await__(self) -> typing.Iterator[T_a]: yield return self.value class AsyncIteratorWrapper(AsyncIterator[T_a]): def __init__(self, value: Iterable[T_a]): self.value = value def __aiter__(self) -> AsyncIterator[T_a]: return self @asyncio.coroutine def __anext__(self) -> T_a: data = yield from self.value if data: return data else: raise StopAsyncIteration class ACM: async def __aenter__(self) -> int: return 42 async def __aexit__(self, etype, eval, tb): return None """ if ASYNCIO: try: exec(ASYNCIO_TESTS) except ImportError: ASYNCIO = False else: # fake names for the sake of static analysis asyncio = None AwaitableWrapper = AsyncIteratorWrapper = ACM = object PY36_TESTS = """ from test import ann_module, ann_module2, ann_module3 from typing_extensions import AsyncContextManager from typing import NamedTuple class A: y: float class B(A): x: ClassVar[Optional['B']] = None y: int b: int class CSub(B): z: ClassVar['CSub'] = B() class G(Generic[T]): lst: ClassVar[List[T]] = [] class Loop: attr: Final['Loop'] class NoneAndForward: parent: 'NoneAndForward' meaning: None class XRepr(NamedTuple): x: int y: int = 1 def __str__(self): return f'{self.x} -> {self.y}' def __add__(self, other): return 0 @runtime class HasCallProtocol(Protocol): __call__: typing.Callable async def g_with(am: AsyncContextManager[int]): x: int async with am as x: return x try: g_with(ACM()).send(None) except StopIteration as e: assert e.args[0] == 42 Label = TypedDict('Label', [('label', str)]) class Point2D(TypedDict): x: int y: int class LabelPoint2D(Point2D, Label): ... class Options(TypedDict, total=False): log_level: int log_path: str """ if PY36: exec(PY36_TESTS) else: # fake names for the sake of static analysis ann_module = ann_module2 = ann_module3 = None A = B = CSub = G = CoolEmployee = CoolEmployeeWithDefault = object XMeth = XRepr = HasCallProtocol = NoneAndForward = Loop = object Point2D = LabelPoint2D = Options = object gth = get_type_hints class GetTypeHintTests(BaseTestCase): @skipUnless(PY36, 'Python 3.6 required') def test_get_type_hints_modules(self): ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str} self.assertEqual(gth(ann_module), ann_module_type_hints) self.assertEqual(gth(ann_module2), {}) self.assertEqual(gth(ann_module3), {}) @skipUnless(PY36, 'Python 3.6 required') def test_get_type_hints_classes(self): self.assertEqual(gth(ann_module.C, ann_module.__dict__), {'y': Optional[ann_module.C]}) self.assertIsInstance(gth(ann_module.j_class), dict) self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type}) self.assertEqual(gth(ann_module.D), {'j': str, 'k': str, 'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.Y), {'z': int}) self.assertEqual(gth(ann_module.h_class), {'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.S), {'x': str, 'y': str}) self.assertEqual(gth(ann_module.foo), {'x': int}) self.assertEqual(gth(NoneAndForward, globals()), {'parent': NoneAndForward, 'meaning': type(None)}) @skipUnless(PY36, 'Python 3.6 required') def test_respect_no_type_check(self): @no_type_check class NoTpCheck: class Inn: def __init__(self, x: 'not a type'): ... # noqa self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) self.assertEqual(gth(ann_module2.NTC.meth), {}) class ABase(Generic[T]): def meth(x: int): ... @no_type_check class Der(ABase): ... self.assertEqual(gth(ABase.meth), {'x': int}) @skipUnless(PY36, 'Python 3.6 required') def test_get_type_hints_ClassVar(self): self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__), {'var': ClassVar[ann_module2.CV]}) self.assertEqual(gth(B, globals()), {'y': int, 'x': ClassVar[Optional[B]], 'b': int}) self.assertEqual(gth(CSub, globals()), {'z': ClassVar[CSub], 'y': int, 'b': int, 'x': ClassVar[Optional[B]]}) self.assertEqual(gth(G), {'lst': ClassVar[List[T]]}) @skipUnless(PY36, 'Python 3.6 required') def test_final_forward_ref(self): self.assertEqual(gth(Loop, globals())['attr'], Final[Loop]) self.assertNotEqual(gth(Loop, globals())['attr'], Final[int]) self.assertNotEqual(gth(Loop, globals())['attr'], Final) class CollectionsAbcTests(BaseTestCase): def test_isinstance_collections(self): self.assertNotIsInstance(1, collections_abc.Mapping) self.assertNotIsInstance(1, collections_abc.Iterable) self.assertNotIsInstance(1, collections_abc.Container) self.assertNotIsInstance(1, collections_abc.Sized) if SUBCLASS_CHECK_FORBIDDEN: with self.assertRaises(TypeError): isinstance(collections.deque(), typing_extensions.Deque[int]) with self.assertRaises(TypeError): issubclass(collections.Counter, typing_extensions.Counter[str]) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_awaitable(self): ns = {} exec( "async def foo() -> typing_extensions.Awaitable[int]:\n" " return await AwaitableWrapper(42)\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing_extensions.Awaitable) self.assertNotIsInstance(foo, typing_extensions.Awaitable) g.send(None) # Run foo() till completion, to avoid warning. @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_coroutine(self): ns = {} exec( "async def foo():\n" " return\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing_extensions.Coroutine) with self.assertRaises(TypeError): isinstance(g, typing_extensions.Coroutine[int]) self.assertNotIsInstance(foo, typing_extensions.Coroutine) try: g.send(None) except StopIteration: pass @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterable(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing_extensions.AsyncIterable) self.assertIsInstance(it, typing_extensions.AsyncIterable) self.assertNotIsInstance(42, typing_extensions.AsyncIterable) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterator(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) if TYPING_3_5_1: self.assertIsInstance(it, typing_extensions.AsyncIterator) self.assertNotIsInstance(42, typing_extensions.AsyncIterator) def test_deque(self): self.assertIsSubclass(collections.deque, typing_extensions.Deque) class MyDeque(typing_extensions.Deque[int]): ... self.assertIsInstance(MyDeque(), collections.deque) def test_counter(self): self.assertIsSubclass(collections.Counter, typing_extensions.Counter) @skipUnless(CAN_INSTANTIATE_COLLECTIONS, "Behavior added in typing 3.6.1") def test_defaultdict_instantiation(self): self.assertIs( type(typing_extensions.DefaultDict()), collections.defaultdict) self.assertIs( type(typing_extensions.DefaultDict[KT, VT]()), collections.defaultdict) self.assertIs( type(typing_extensions.DefaultDict[str, int]()), collections.defaultdict) def test_defaultdict_subclass(self): class MyDefDict(typing_extensions.DefaultDict[str, int]): pass dd = MyDefDict() self.assertIsInstance(dd, MyDefDict) self.assertIsSubclass(MyDefDict, collections.defaultdict) if TYPING_3_5_3: self.assertNotIsSubclass(collections.defaultdict, MyDefDict) def test_chainmap_instantiation(self): self.assertIs(type(typing_extensions.ChainMap()), collections.ChainMap) self.assertIs(type(typing_extensions.ChainMap[KT, VT]()), collections.ChainMap) self.assertIs(type(typing_extensions.ChainMap[str, int]()), collections.ChainMap) class CM(typing_extensions.ChainMap[KT, VT]): ... if TYPING_3_5_3: self.assertIs(type(CM[int, str]()), CM) def test_chainmap_subclass(self): class MyChainMap(typing_extensions.ChainMap[str, int]): pass cm = MyChainMap() self.assertIsInstance(cm, MyChainMap) self.assertIsSubclass(MyChainMap, collections.ChainMap) if TYPING_3_5_3: self.assertNotIsSubclass(collections.ChainMap, MyChainMap) def test_deque_instantiation(self): self.assertIs(type(typing_extensions.Deque()), collections.deque) self.assertIs(type(typing_extensions.Deque[T]()), collections.deque) self.assertIs(type(typing_extensions.Deque[int]()), collections.deque) class D(typing_extensions.Deque[T]): ... if TYPING_3_5_3: self.assertIs(type(D[int]()), D) def test_counter_instantiation(self): self.assertIs(type(typing_extensions.Counter()), collections.Counter) self.assertIs(type(typing_extensions.Counter[T]()), collections.Counter) self.assertIs(type(typing_extensions.Counter[int]()), collections.Counter) class C(typing_extensions.Counter[T]): ... if TYPING_3_5_3: self.assertIs(type(C[int]()), C) if not PEP_560: self.assertEqual(C.__bases__, (typing_extensions.Counter,)) else: self.assertEqual(C.__bases__, (collections.Counter, typing.Generic)) def test_counter_subclass_instantiation(self): class MyCounter(typing_extensions.Counter[int]): pass d = MyCounter() self.assertIsInstance(d, MyCounter) self.assertIsInstance(d, collections.Counter) if TYPING_3_5_1: self.assertIsInstance(d, typing_extensions.Counter) @skipUnless(PY36, 'Python 3.6 required') def test_async_generator(self): ns = {} exec("async def f():\n" " yield 42\n", globals(), ns) g = ns['f']() self.assertIsSubclass(type(g), typing_extensions.AsyncGenerator) @skipUnless(PY36, 'Python 3.6 required') def test_no_async_generator_instantiation(self): with self.assertRaises(TypeError): typing_extensions.AsyncGenerator() with self.assertRaises(TypeError): typing_extensions.AsyncGenerator[T, T]() with self.assertRaises(TypeError): typing_extensions.AsyncGenerator[int, int]() @skipUnless(PY36, 'Python 3.6 required') def test_subclassing_async_generator(self): class G(typing_extensions.AsyncGenerator[int, int]): def asend(self, value): pass def athrow(self, typ, val=None, tb=None): pass ns = {} exec('async def g(): yield 0', globals(), ns) g = ns['g'] self.assertIsSubclass(G, typing_extensions.AsyncGenerator) self.assertIsSubclass(G, typing_extensions.AsyncIterable) self.assertIsSubclass(G, collections_abc.AsyncGenerator) self.assertIsSubclass(G, collections_abc.AsyncIterable) self.assertNotIsSubclass(type(g), G) instance = G() self.assertIsInstance(instance, typing_extensions.AsyncGenerator) self.assertIsInstance(instance, typing_extensions.AsyncIterable) self.assertIsInstance(instance, collections_abc.AsyncGenerator) self.assertIsInstance(instance, collections_abc.AsyncIterable) self.assertNotIsInstance(type(g), G) self.assertNotIsInstance(g, G) class OtherABCTests(BaseTestCase): def test_contextmanager(self): @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertIsInstance(cm, typing_extensions.ContextManager) self.assertNotIsInstance(42, typing_extensions.ContextManager) @skipUnless(ASYNCIO, 'Python 3.5 required') def test_async_contextmanager(self): class NotACM: pass self.assertIsInstance(ACM(), typing_extensions.AsyncContextManager) self.assertNotIsInstance(NotACM(), typing_extensions.AsyncContextManager) @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertNotIsInstance(cm, typing_extensions.AsyncContextManager) if TYPING_3_5_3: self.assertEqual(typing_extensions.AsyncContextManager[int].__args__, (int,)) if TYPING_3_6_1: with self.assertRaises(TypeError): isinstance(42, typing_extensions.AsyncContextManager[int]) with self.assertRaises(TypeError): typing_extensions.AsyncContextManager[int, str] class TypeTests(BaseTestCase): def test_type_basic(self): class User: pass class BasicUser(User): pass class ProUser(User): pass def new_user(user_class: Type[User]) -> User: return user_class() new_user(BasicUser) def test_type_typevar(self): class User: pass class BasicUser(User): pass class ProUser(User): pass U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: return user_class() new_user(BasicUser) @skipUnless(sys.version_info[:3] != (3, 5, 2), 'Python 3.5.2 has a somewhat buggy Type impl') def test_type_optional(self): A = Optional[Type[BaseException]] def foo(a: A) -> Optional[BaseException]: if a is None: return None else: return a() assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt) assert foo(None) is None class NewTypeTests(BaseTestCase): def test_basic(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) self.assertIsInstance(UserId(5), int) self.assertIsInstance(UserName('Joe'), str) self.assertEqual(UserId(5) + 1, 6) def test_errors(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) with self.assertRaises(TypeError): issubclass(UserId, int) with self.assertRaises(TypeError): class D(UserName): pass PY36_PROTOCOL_TESTS = """ class Coordinate(Protocol): x: int y: int @runtime class Point(Coordinate, Protocol): label: str class MyPoint: x: int y: int label: str class XAxis(Protocol): x: int class YAxis(Protocol): y: int @runtime class Position(XAxis, YAxis, Protocol): pass @runtime class Proto(Protocol): attr: int def meth(self, arg: str) -> int: ... class Concrete(Proto): pass class Other: attr: int = 1 def meth(self, arg: str) -> int: if arg == 'this': return 1 return 0 class NT(NamedTuple): x: int y: int """ if PY36: exec(PY36_PROTOCOL_TESTS) else: # fake names for the sake of static analysis Coordinate = Point = MyPoint = BadPoint = NT = object XAxis = YAxis = Position = Proto = Concrete = Other = object if HAVE_PROTOCOLS: class ProtocolTests(BaseTestCase): def test_basic_protocol(self): @runtime class P(Protocol): def meth(self): pass class C: pass class D: def meth(self): pass def f(): pass self.assertIsSubclass(D, P) self.assertIsInstance(D(), P) self.assertNotIsSubclass(C, P) self.assertNotIsInstance(C(), P) self.assertNotIsSubclass(types.FunctionType, P) self.assertNotIsInstance(f, P) def test_everything_implements_empty_protocol(self): @runtime class Empty(Protocol): pass class C: pass def f(): pass for thing in (object, type, tuple, C, types.FunctionType): self.assertIsSubclass(thing, Empty) for thing in (object(), 1, (), typing, f): self.assertIsInstance(thing, Empty) @skipUnless(PY36, 'Python 3.6 required') def test_function_implements_protocol(self): def f(): pass self.assertIsInstance(f, HasCallProtocol) def test_no_inheritance_from_nominal(self): class C: pass class BP(Protocol): pass with self.assertRaises(TypeError): class P(C, Protocol): pass with self.assertRaises(TypeError): class P(Protocol, C): pass with self.assertRaises(TypeError): class P(BP, C, Protocol): pass class D(BP, C): pass class E(C, BP): pass self.assertNotIsInstance(D(), E) self.assertNotIsInstance(E(), D) def test_no_instantiation(self): class P(Protocol): pass with self.assertRaises(TypeError): P() class C(P): pass self.assertIsInstance(C(), C) T = TypeVar('T') class PG(Protocol[T]): pass with self.assertRaises(TypeError): PG() with self.assertRaises(TypeError): PG[int]() with self.assertRaises(TypeError): PG[T]() class CG(PG[T]): pass self.assertIsInstance(CG[int](), CG) def test_cannot_instantiate_abstract(self): @runtime class P(Protocol): @abc.abstractmethod def ameth(self) -> int: raise NotImplementedError class B(P): pass class C(B): def ameth(self) -> int: return 26 with self.assertRaises(TypeError): B() self.assertIsInstance(C(), P) def test_subprotocols_extending(self): class P1(Protocol): def meth1(self): pass @runtime class P2(P1, Protocol): def meth2(self): pass class C: def meth1(self): pass def meth2(self): pass class C1: def meth1(self): pass class C2: def meth2(self): pass self.assertNotIsInstance(C1(), P2) self.assertNotIsInstance(C2(), P2) self.assertNotIsSubclass(C1, P2) self.assertNotIsSubclass(C2, P2) self.assertIsInstance(C(), P2) self.assertIsSubclass(C, P2) def test_subprotocols_merging(self): class P1(Protocol): def meth1(self): pass class P2(Protocol): def meth2(self): pass @runtime class P(P1, P2, Protocol): pass class C: def meth1(self): pass def meth2(self): pass class C1: def meth1(self): pass class C2: def meth2(self): pass self.assertNotIsInstance(C1(), P) self.assertNotIsInstance(C2(), P) self.assertNotIsSubclass(C1, P) self.assertNotIsSubclass(C2, P) self.assertIsInstance(C(), P) self.assertIsSubclass(C, P) def test_protocols_issubclass(self): T = TypeVar('T') @runtime class P(Protocol): def x(self): ... @runtime class PG(Protocol[T]): def x(self): ... class BadP(Protocol): def x(self): ... class BadPG(Protocol[T]): def x(self): ... class C: def x(self): ... self.assertIsSubclass(C, P) self.assertIsSubclass(C, PG) self.assertIsSubclass(BadP, PG) if not PEP_560: self.assertIsSubclass(PG[int], PG) self.assertIsSubclass(BadPG[int], P) self.assertIsSubclass(BadPG[T], PG) with self.assertRaises(TypeError): issubclass(C, PG[T]) with self.assertRaises(TypeError): issubclass(C, PG[C]) with self.assertRaises(TypeError): issubclass(C, BadP) with self.assertRaises(TypeError): issubclass(C, BadPG) with self.assertRaises(TypeError): issubclass(P, PG[T]) with self.assertRaises(TypeError): issubclass(PG, PG[int]) def test_protocols_issubclass_non_callable(self): class C: x = 1 @runtime class PNonCall(Protocol): x = 1 with self.assertRaises(TypeError): issubclass(C, PNonCall) self.assertIsInstance(C(), PNonCall) PNonCall.register(C) with self.assertRaises(TypeError): issubclass(C, PNonCall) self.assertIsInstance(C(), PNonCall) # check that non-protocol subclasses are not affected class D(PNonCall): ... self.assertNotIsSubclass(C, D) self.assertNotIsInstance(C(), D) D.register(C) self.assertIsSubclass(C, D) self.assertIsInstance(C(), D) with self.assertRaises(TypeError): issubclass(D, PNonCall) def test_protocols_isinstance(self): T = TypeVar('T') @runtime class P(Protocol): def meth(x): ... @runtime class PG(Protocol[T]): def meth(x): ... class BadP(Protocol): def meth(x): ... class BadPG(Protocol[T]): def meth(x): ... class C: def meth(x): ... self.assertIsInstance(C(), P) self.assertIsInstance(C(), PG) with self.assertRaises(TypeError): isinstance(C(), PG[T]) with self.assertRaises(TypeError): isinstance(C(), PG[C]) with self.assertRaises(TypeError): isinstance(C(), BadP) with self.assertRaises(TypeError): isinstance(C(), BadPG) @skipUnless(PY36, 'Python 3.6 required') def test_protocols_isinstance_py36(self): class APoint: def __init__(self, x, y, label): self.x = x self.y = y self.label = label class BPoint: label = 'B' def __init__(self, x, y): self.x = x self.y = y class C: def __init__(self, attr): self.attr = attr def meth(self, arg): return 0 class Bad: pass self.assertIsInstance(APoint(1, 2, 'A'), Point) self.assertIsInstance(BPoint(1, 2), Point) self.assertNotIsInstance(MyPoint(), Point) self.assertIsInstance(BPoint(1, 2), Position) self.assertIsInstance(Other(), Proto) self.assertIsInstance(Concrete(), Proto) self.assertIsInstance(C(42), Proto) self.assertNotIsInstance(Bad(), Proto) self.assertNotIsInstance(Bad(), Point) self.assertNotIsInstance(Bad(), Position) self.assertNotIsInstance(Bad(), Concrete) self.assertNotIsInstance(Other(), Concrete) self.assertIsInstance(NT(1, 2), Position) def test_protocols_isinstance_init(self): T = TypeVar('T') @runtime class P(Protocol): x = 1 @runtime class PG(Protocol[T]): x = 1 class C: def __init__(self, x): self.x = x self.assertIsInstance(C(1), P) self.assertIsInstance(C(1), PG) def test_protocols_support_register(self): @runtime class P(Protocol): x = 1 class PM(Protocol): def meth(self): pass class D(PM): pass class C: pass D.register(C) P.register(C) self.assertIsInstance(C(), P) self.assertIsInstance(C(), D) def test_none_on_non_callable_doesnt_block_implementation(self): @runtime class P(Protocol): x = 1 class A: x = 1 class B(A): x = None class C: def __init__(self): self.x = None self.assertIsInstance(B(), P) self.assertIsInstance(C(), P) def test_none_on_callable_blocks_implementation(self): @runtime class P(Protocol): def x(self): ... class A: def x(self): ... class B(A): x = None class C: def __init__(self): self.x = None self.assertNotIsInstance(B(), P) self.assertNotIsInstance(C(), P) def test_non_protocol_subclasses(self): class P(Protocol): x = 1 @runtime class PR(Protocol): def meth(self): pass class NonP(P): x = 1 class NonPR(PR): pass class C: x = 1 class D: def meth(self): pass self.assertNotIsInstance(C(), NonP) self.assertNotIsInstance(D(), NonPR) self.assertNotIsSubclass(C, NonP) self.assertNotIsSubclass(D, NonPR) self.assertIsInstance(NonPR(), PR) self.assertIsSubclass(NonPR, PR) def test_custom_subclasshook(self): class P(Protocol): x = 1 class OKClass: pass class BadClass: x = 1 class C(P): @classmethod def __subclasshook__(cls, other): return other.__name__.startswith("OK") self.assertIsInstance(OKClass(), C) self.assertNotIsInstance(BadClass(), C) self.assertIsSubclass(OKClass, C) self.assertNotIsSubclass(BadClass, C) def test_issubclass_fails_correctly(self): @runtime class P(Protocol): x = 1 class C: pass with self.assertRaises(TypeError): issubclass(C(), P) @skipUnless(not OLD_GENERICS, "New style generics required") def test_defining_generic_protocols(self): T = TypeVar('T') S = TypeVar('S') @runtime class PR(Protocol[T, S]): def meth(self): pass class P(PR[int, T], Protocol[T]): y = 1 self.assertIsSubclass(PR[int, T], PR) self.assertIsSubclass(P[str], PR) with self.assertRaises(TypeError): PR[int] with self.assertRaises(TypeError): P[int, str] with self.assertRaises(TypeError): PR[int, 1] if TYPING_3_5_3: with self.assertRaises(TypeError): PR[int, ClassVar] class C(PR[int, T]): pass self.assertIsInstance(C[str](), C) def test_defining_generic_protocols_old_style(self): T = TypeVar('T') S = TypeVar('S') @runtime class PR(Protocol, Generic[T, S]): def meth(self): pass class P(PR[int, str], Protocol): y = 1 if not PEP_560: self.assertIsSubclass(PR[int, str], PR) else: with self.assertRaises(TypeError): self.assertIsSubclass(PR[int, str], PR) self.assertIsSubclass(P, PR) with self.assertRaises(TypeError): PR[int] with self.assertRaises(TypeError): PR[int, 1] class P1(Protocol, Generic[T]): def bar(self, x: T) -> str: ... class P2(Generic[T], Protocol): def bar(self, x: T) -> str: ... @runtime class PSub(P1[str], Protocol): x = 1 class Test: x = 1 def bar(self, x: str) -> str: return x self.assertIsInstance(Test(), PSub) if TYPING_3_5_3: with self.assertRaises(TypeError): PR[int, ClassVar] def test_init_called(self): T = TypeVar('T') class P(Protocol[T]): pass class C(P[T]): def __init__(self): self.test = 'OK' self.assertEqual(C[int]().test, 'OK') @skipUnless(not OLD_GENERICS, "New style generics required") def test_protocols_bad_subscripts(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): class P(Protocol[T, T]): pass with self.assertRaises(TypeError): class P(Protocol[int]): pass with self.assertRaises(TypeError): class P(Protocol[T], Protocol[S]): pass with self.assertRaises(TypeError): class P(typing.Mapping[T, S], Protocol[T]): pass @skipUnless(TYPING_3_5_3, 'New style __repr__ and __eq__ only') def test_generic_protocols_repr(self): T = TypeVar('T') S = TypeVar('S') class P(Protocol[T, S]): pass # After PEP 560 unsubscripted generics have a standard repr. if not PEP_560: self.assertTrue(repr(P).endswith('P')) self.assertTrue(repr(P[T, S]).endswith('P[~T, ~S]')) self.assertTrue(repr(P[int, str]).endswith('P[int, str]')) @skipUnless(TYPING_3_5_3, 'New style __repr__ and __eq__ only') def test_generic_protocols_eq(self): T = TypeVar('T') S = TypeVar('S') class P(Protocol[T, S]): pass self.assertEqual(P, P) self.assertEqual(P[int, T], P[int, T]) self.assertEqual(P[T, T][Tuple[T, S]][int, str], P[Tuple[int, str], Tuple[int, str]]) @skipUnless(not OLD_GENERICS, "New style generics required") def test_generic_protocols_special_from_generic(self): T = TypeVar('T') class P(Protocol[T]): pass self.assertEqual(P.__parameters__, (T,)) self.assertIs(P.__args__, None) self.assertIs(P.__origin__, None) self.assertEqual(P[int].__parameters__, ()) self.assertEqual(P[int].__args__, (int,)) self.assertIs(P[int].__origin__, P) def test_generic_protocols_special_from_protocol(self): @runtime class PR(Protocol): x = 1 class P(Protocol): def meth(self): pass T = TypeVar('T') class PG(Protocol[T]): x = 1 def meth(self): pass self.assertTrue(P._is_protocol) self.assertTrue(PR._is_protocol) self.assertTrue(PG._is_protocol) if hasattr(typing, 'Protocol'): self.assertFalse(P._is_runtime_protocol) else: with self.assertRaises(AttributeError): self.assertFalse(P._is_runtime_protocol) self.assertTrue(PR._is_runtime_protocol) self.assertTrue(PG[int]._is_protocol) self.assertEqual(typing_extensions._get_protocol_attrs(P), {'meth'}) self.assertEqual(typing_extensions._get_protocol_attrs(PR), {'x'}) self.assertEqual(frozenset(typing_extensions._get_protocol_attrs(PG)), frozenset({'x', 'meth'})) if not PEP_560: self.assertEqual(frozenset(typing_extensions._get_protocol_attrs(PG[int])), frozenset({'x', 'meth'})) def test_no_runtime_deco_on_nominal(self): with self.assertRaises(TypeError): @runtime class C: pass class Proto(Protocol): x = 1 with self.assertRaises(TypeError): @runtime class Concrete(Proto): pass def test_none_treated_correctly(self): @runtime class P(Protocol): x = None # type: int class B(object): pass self.assertNotIsInstance(B(), P) class C: x = 1 class D: x = None self.assertIsInstance(C(), P) self.assertIsInstance(D(), P) class CI: def __init__(self): self.x = 1 class DI: def __init__(self): self.x = None self.assertIsInstance(C(), P) self.assertIsInstance(D(), P) def test_protocols_in_unions(self): class P(Protocol): x = None # type: int Alias = typing.Union[typing.Iterable, P] Alias2 = typing.Union[P, typing.Iterable] self.assertEqual(Alias, Alias2) def test_protocols_pickleable(self): global P, CP # pickle wants to reference the class by name T = TypeVar('T') @runtime class P(Protocol[T]): x = 1 class CP(P[int]): pass c = CP() c.foo = 42 c.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(c, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.x, 1) self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) s = pickle.dumps(P) D = pickle.loads(s) class E: x = 1 self.assertIsInstance(E(), D) def test_collections_protocols_allowed(self): @runtime_checkable class Custom(collections.abc.Iterable, Protocol): def close(self): pass class A: ... class B: def __iter__(self): return [] def close(self): return 0 self.assertIsSubclass(B, Custom) self.assertNotIsSubclass(A, Custom) class TypedDictTests(BaseTestCase): def test_basics_iterable_syntax(self): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) if sys.version_info[0] >= 3: import collections.abc self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_basics_keywords_syntax(self): Emp = TypedDict('Emp', name=str, id=int) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) if sys.version_info[0] >= 3: import collections.abc self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_typeddict_errors(self): Emp = TypedDict('Emp', {'name': str, 'id': int}) if hasattr(typing, 'TypedDict'): self.assertEqual(TypedDict.__module__, 'typing') else: self.assertEqual(TypedDict.__module__, 'typing_extensions') jim = Emp(name='Jim', id=1) with self.assertRaises(TypeError): isinstance({}, Emp) with self.assertRaises(TypeError): isinstance(jim, Emp) with self.assertRaises(TypeError): issubclass(dict, Emp) with self.assertRaises(TypeError): TypedDict('Hi', x=1) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int), ('y', 1)]) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int)], y=int) @skipUnless(PY36, 'Python 3.6 required') def test_py36_class_syntax_usage(self): self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D') self.assertEqual(LabelPoint2D.__module__, __name__) self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str}) self.assertEqual(LabelPoint2D.__bases__, (dict,)) self.assertEqual(LabelPoint2D.__total__, True) self.assertNotIsSubclass(LabelPoint2D, typing.Sequence) not_origin = Point2D(x=0, y=1) self.assertEqual(not_origin['x'], 0) self.assertEqual(not_origin['y'], 1) other = LabelPoint2D(x=0, y=1, label='hi') self.assertEqual(other['label'], 'hi') def test_pickle(self): global EmpD # pickle wants to reference the class by name EmpD = TypedDict('EmpD', name=str, id=int) jane = EmpD({'name': 'jane', 'id': 37}) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) self.assertEqual(jane2, {'name': 'jane', 'id': 37}) ZZ = pickle.dumps(EmpD, proto) EmpDnew = pickle.loads(ZZ) self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane) def test_optional(self): EmpD = TypedDict('EmpD', name=str, id=int) self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD]) self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD]) def test_total(self): D = TypedDict('D', {'x': int}, total=False) self.assertEqual(D(), {}) self.assertEqual(D(x=1), {'x': 1}) self.assertEqual(D.__total__, False) if PY36: self.assertEqual(Options(), {}) self.assertEqual(Options(log_level=2), {'log_level': 2}) self.assertEqual(Options.__total__, False) @skipUnless(TYPING_3_5_3, "Python >= 3.5.3 required") class AnnotatedTests(BaseTestCase): def test_repr(self): self.assertEqual( repr(Annotated[int, 4, 5]), "typing_extensions.Annotated[int, 4, 5]" ) self.assertEqual( repr(Annotated[List[int], 4, 5]), "typing_extensions.Annotated[typing.List[int], 4, 5]" ) def test_flatten(self): A = Annotated[Annotated[int, 4], 5] self.assertEqual(A, Annotated[int, 4, 5]) self.assertEqual(A.__metadata__, (4, 5)) if PEP_560: self.assertEqual(A.__origin__, int) def test_specialize(self): L = Annotated[List[T], "my decoration"] LI = Annotated[List[int], "my decoration"] self.assertEqual(L[int], Annotated[List[int], "my decoration"]) self.assertEqual(L[int].__metadata__, ("my decoration",)) if PEP_560: self.assertEqual(L[int].__origin__, List[int]) with self.assertRaises(TypeError): LI[int] with self.assertRaises(TypeError): L[int, float] def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_instantiate(self): class C: classvar = 4 def __init__(self, x): self.x = x def __eq__(self, other): if not isinstance(other, C): return NotImplemented return other.x == self.x A = Annotated[C, "a decoration"] a = A(5) c = C(5) self.assertEqual(a, c) self.assertEqual(a.x, c.x) self.assertEqual(a.classvar, c.classvar) def test_instantiate_generic(self): MyCount = Annotated[typing_extensions.Counter[T], "my decoration"] self.assertEqual(MyCount([4, 4, 5]), {4: 2, 5: 1}) self.assertEqual(MyCount[int]([4, 4, 5]), {4: 2, 5: 1}) def test_cannot_instantiate_forward(self): A = Annotated["int", (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_instantiate_type_var(self): A = Annotated[T, (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_getattr_typevar(self): with self.assertRaises(AttributeError): Annotated[T, (5, 7)].x def test_attr_passthrough(self): class C: classvar = 4 A = Annotated[C, "a decoration"] self.assertEqual(A.classvar, 4) A.x = 5 self.assertEqual(C.x, 5) def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_cannot_subclass(self): with self.assertRaisesRegex(TypeError, "Cannot subclass .*Annotated"): class C(Annotated): pass def test_cannot_check_instance(self): with self.assertRaises(TypeError): isinstance(5, Annotated[int, "positive"]) def test_cannot_check_subclass(self): with self.assertRaises(TypeError): issubclass(int, Annotated[int, "positive"]) @skipUnless(PEP_560, "pickle support was added with PEP 560") def test_pickle(self): samples = [typing.Any, typing.Union[int, str], typing.Optional[str], Tuple[int, ...], typing.Callable[[str], bytes]] for t in samples: x = Annotated[t, "a"] for prot in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(protocol=prot, type=t): pickled = pickle.dumps(x, prot) restored = pickle.loads(pickled) self.assertEqual(x, restored) global _Annotated_test_G class _Annotated_test_G(Generic[T]): x = 1 G = Annotated[_Annotated_test_G[int], "A decoration"] G.foo = 42 G.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(G, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.x, 1) def test_subst(self): dec = "a decoration" dec2 = "another decoration" S = Annotated[T, dec2] self.assertEqual(S[int], Annotated[int, dec2]) self.assertEqual(S[Annotated[int, dec]], Annotated[int, dec, dec2]) L = Annotated[List[T], dec] self.assertEqual(L[int], Annotated[List[int], dec]) with self.assertRaises(TypeError): L[int, int] self.assertEqual(S[L[int]], Annotated[List[int], dec, dec2]) D = Annotated[Dict[KT, VT], dec] self.assertEqual(D[str, int], Annotated[Dict[str, int], dec]) with self.assertRaises(TypeError): D[int] It = Annotated[int, dec] with self.assertRaises(TypeError): It[None] LI = L[int] with self.assertRaises(TypeError): LI[None] def test_annotated_in_other_types(self): X = List[Annotated[T, 5]] self.assertEqual(X[int], List[Annotated[int, 5]]) @skipUnless(PEP_560, "Python 3.7 required") class GetTypeHintsTests(BaseTestCase): def test_get_type_hints(self): def foobar(x: List['X']): ... X = Annotated[int, (1, 10)] self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': List[int]} ) self.assertEqual( get_type_hints(foobar, globals(), locals(), include_extras=True), {'x': List[Annotated[int, (1, 10)]]} ) BA = Tuple[Annotated[T, (1, 0)], ...] def barfoo(x: BA): ... self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], Tuple[T, ...]) self.assertIs( get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'], BA ) def barfoo2(x: typing.Callable[..., Annotated[List[T], "const"]], y: typing.Union[int, Annotated[T, "mutable"]]): ... self.assertEqual( get_type_hints(barfoo2, globals(), locals()), {'x': typing.Callable[..., List[T]], 'y': typing.Union[int, T]} ) BA2 = typing.Callable[..., List[T]] def barfoo3(x: BA2): ... self.assertIs( get_type_hints(barfoo3, globals(), locals(), include_extras=True)["x"], BA2 ) def test_get_type_hints_refs(self): Const = Annotated[T, "Const"] class MySet(Generic[T]): def __ior__(self, other: "Const[MySet[T]]") -> "MySet[T]": ... def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]": ... self.assertEqual( get_type_hints(MySet.__iand__, globals(), locals()), {'other': MySet[T], 'return': MySet[T]} ) self.assertEqual( get_type_hints(MySet.__iand__, globals(), locals(), include_extras=True), {'other': Const[MySet[T]], 'return': MySet[T]} ) self.assertEqual( get_type_hints(MySet.__ior__, globals(), locals()), {'other': MySet[T], 'return': MySet[T]} ) class AllTests(BaseTestCase): def test_typing_extensions_includes_standard(self): a = typing_extensions.__all__ self.assertIn('ClassVar', a) self.assertIn('Type', a) self.assertIn('ChainMap', a) self.assertIn('ContextManager', a) self.assertIn('Counter', a) self.assertIn('DefaultDict', a) self.assertIn('Deque', a) self.assertIn('NewType', a) self.assertIn('overload', a) self.assertIn('Text', a) self.assertIn('TYPE_CHECKING', a) if TYPING_3_5_3: self.assertIn('Annotated', a) if PEP_560: self.assertIn('get_type_hints', a) if ASYNCIO: self.assertIn('Awaitable', a) self.assertIn('AsyncIterator', a) self.assertIn('AsyncIterable', a) self.assertIn('Coroutine', a) self.assertIn('AsyncContextManager', a) if PY36: self.assertIn('AsyncGenerator', a) if TYPING_3_5_3: self.assertIn('Protocol', a) self.assertIn('runtime', a) def test_typing_extensions_defers_when_possible(self): exclude = {'overload', 'Text', 'TYPE_CHECKING', 'Final', 'get_type_hints'} for item in typing_extensions.__all__: if item not in exclude and hasattr(typing, item): self.assertIs( getattr(typing_extensions, item), getattr(typing, item)) def test_typing_extensions_compiles_with_opt(self): file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'typing_extensions.py') try: subprocess.check_output('{} -OO {}'.format(sys.executable, file_path), stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError: self.fail('Module does not compile with optimize=2 (-OO flag).') if __name__ == '__main__': main() typing_extensions-3.7.4.1/src_py3/typing_extensions.egg-info/0000755000175000017500000000000013555566352024255 5ustar ivanivan00000000000000typing_extensions-3.7.4.1/src_py3/typing_extensions.egg-info/requires.txt0000644000175000017500000000005113555566352026651 0ustar ivanivan00000000000000 [:python_version < "3.5"] typing>=3.7.4 typing_extensions-3.7.4.1/src_py3/typing_extensions.egg-info/PKG-INFO0000644000175000017500000000372213555566352025356 0ustar ivanivan00000000000000Metadata-Version: 1.1 Name: typing-extensions Version: 3.7.4.1 Summary: Backported and Experimental Type Hints for Python 3.5+ Home-page: https://github.com/python/typing/blob/master/typing_extensions/README.rst Author: Guido van Rossum, Jukka Lehtosalo, Lukasz Langa, Michael Lee Author-email: levkivskyi@gmail.com License: PSF Description: Typing Extensions -- Backported and Experimental Type Hints for Python The ``typing`` module was added to the standard library in Python 3.5 on a provisional basis and will no longer be provisional in Python 3.7. However, this means users of Python 3.5 - 3.6 who are unable to upgrade will not be able to take advantage of new types added to the ``typing`` module, such as ``typing.Text`` or ``typing.Coroutine``. The ``typing_extensions`` module contains both backports of these changes as well as experimental types that will eventually be added to the ``typing`` module, such as ``Protocol`` or ``TypedDict``. Users of other Python versions should continue to install and use the ``typing`` module from PyPi instead of using this one unless specifically writing code that must be compatible with multiple Python versions or requires experimental types. Keywords: typing function annotations type hints hinting checking checker typehints typehinting typechecking backport Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Software Development typing_extensions-3.7.4.1/src_py3/typing_extensions.egg-info/top_level.txt0000644000175000017500000000002213555566352027001 0ustar ivanivan00000000000000typing_extensions typing_extensions-3.7.4.1/src_py3/typing_extensions.egg-info/SOURCES.txt0000644000175000017500000000064313555566352026144 0ustar ivanivan00000000000000LICENSE MANIFEST.in README.rst setup.cfg setup.py src_py2/test_typing_extensions.py src_py2/typing_extensions.py src_py3/test_typing_extensions.py src_py3/typing_extensions.py src_py3/typing_extensions.egg-info/PKG-INFO src_py3/typing_extensions.egg-info/SOURCES.txt src_py3/typing_extensions.egg-info/dependency_links.txt src_py3/typing_extensions.egg-info/requires.txt src_py3/typing_extensions.egg-info/top_level.txttyping_extensions-3.7.4.1/src_py3/typing_extensions.egg-info/dependency_links.txt0000644000175000017500000000000113555566352030323 0ustar ivanivan00000000000000 typing_extensions-3.7.4.1/setup.cfg0000644000175000017500000000011113555566352017222 0ustar ivanivan00000000000000[metadata] license-file = LICENSE [egg_info] tag_build = tag_date = 0 typing_extensions-3.7.4.1/PKG-INFO0000644000175000017500000000372213555566352016511 0ustar ivanivan00000000000000Metadata-Version: 1.1 Name: typing_extensions Version: 3.7.4.1 Summary: Backported and Experimental Type Hints for Python 3.5+ Home-page: https://github.com/python/typing/blob/master/typing_extensions/README.rst Author: Guido van Rossum, Jukka Lehtosalo, Lukasz Langa, Michael Lee Author-email: levkivskyi@gmail.com License: PSF Description: Typing Extensions -- Backported and Experimental Type Hints for Python The ``typing`` module was added to the standard library in Python 3.5 on a provisional basis and will no longer be provisional in Python 3.7. However, this means users of Python 3.5 - 3.6 who are unable to upgrade will not be able to take advantage of new types added to the ``typing`` module, such as ``typing.Text`` or ``typing.Coroutine``. The ``typing_extensions`` module contains both backports of these changes as well as experimental types that will eventually be added to the ``typing`` module, such as ``Protocol`` or ``TypedDict``. Users of other Python versions should continue to install and use the ``typing`` module from PyPi instead of using this one unless specifically writing code that must be compatible with multiple Python versions or requires experimental types. Keywords: typing function annotations type hints hinting checking checker typehints typehinting typechecking backport Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Software Development typing_extensions-3.7.4.1/setup.py0000644000175000017500000000504513555564746017133 0ustar ivanivan00000000000000#!/usr/bin/env python # coding: utf-8 import sys from setuptools import setup if sys.version_info < (2, 7, 0) or (3, 0, 0) <= sys.version_info < (3, 4, 0): sys.stderr.write('ERROR: You need Python 2.7 or 3.4+ ' 'to install the typing package.\n') exit(1) version = '3.7.4.1' description = 'Backported and Experimental Type Hints for Python 3.5+' long_description = '''\ Typing Extensions -- Backported and Experimental Type Hints for Python The ``typing`` module was added to the standard library in Python 3.5 on a provisional basis and will no longer be provisional in Python 3.7. However, this means users of Python 3.5 - 3.6 who are unable to upgrade will not be able to take advantage of new types added to the ``typing`` module, such as ``typing.Text`` or ``typing.Coroutine``. The ``typing_extensions`` module contains both backports of these changes as well as experimental types that will eventually be added to the ``typing`` module, such as ``Protocol`` or ``TypedDict``. Users of other Python versions should continue to install and use the ``typing`` module from PyPi instead of using this one unless specifically writing code that must be compatible with multiple Python versions or requires experimental types. ''' classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Python Software Foundation License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development', ] if sys.version_info.major == 2: package_dir = 'src_py2' elif sys.version_info.major == 3: package_dir = 'src_py3' else: raise AssertionError() setup(name='typing_extensions', version=version, description=description, long_description=long_description, author='Guido van Rossum, Jukka Lehtosalo, Lukasz Langa, Michael Lee', author_email='levkivskyi@gmail.com', url='https://github.com/python/typing/blob/master/typing_extensions/README.rst', license='PSF', keywords='typing function annotations type hints hinting checking ' 'checker typehints typehinting typechecking backport', package_dir={'': package_dir}, py_modules=['typing_extensions'], classifiers=classifiers, install_requires=["typing >= 3.7.4; python_version < '3.5'"]) typing_extensions-3.7.4.1/src_py2/0000755000175000017500000000000013555566352016771 5ustar ivanivan00000000000000typing_extensions-3.7.4.1/src_py2/typing_extensions.py0000644000175000017500000001750613523611432023126 0ustar ivanivan00000000000000import abc import typing from typing import ( # noqa # These are imported for re-export. ClassVar, Type, Generic, Callable, GenericMeta, TypingMeta, Counter, DefaultDict, Deque, TypeVar, Tuple, Final, final, NewType, overload, Text, TYPE_CHECKING, Literal, TypedDict, Protocol, runtime_checkable, # We use internal typing helpers here, but this significantly reduces # code duplication. (Also this is only until Protocol is in typing.) _type_vars, _tp_cache, _type_check, ) # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. 'ClassVar', 'Final', 'Protocol', 'Type', 'TypedDict', # Concrete collection types. 'ContextManager', 'Counter', 'Deque', 'DefaultDict', # One-off things. 'final', 'IntVar', 'Literal', 'NewType', 'overload', 'runtime_checkable', 'Text', 'TYPE_CHECKING', ] if hasattr(typing, 'NoReturn'): NoReturn = typing.NoReturn else: # TODO: Remove once typing.py has been updated class _NoReturnMeta(typing.TypingMeta): """Metaclass for NoReturn.""" def __new__(cls, name, bases, namespace): cls.assert_no_subclassing(bases) self = super(_NoReturnMeta, cls).__new__(cls, name, bases, namespace) return self class _NoReturn(typing._FinalTypingBase): """Special type indicating functions that never return. Example:: from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') This type is invalid in other positions, e.g., ``List[NoReturn]`` will fail in static type checkers. """ __metaclass__ = _NoReturnMeta __slots__ = () def __instancecheck__(self, obj): raise TypeError("NoReturn cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("NoReturn cannot be used with issubclass().") NoReturn = _NoReturn(_root=True) T_co = typing.TypeVar('T_co', covariant=True) if hasattr(typing, 'ContextManager'): ContextManager = typing.ContextManager else: # TODO: Remove once typing.py has been updated class ContextManager(typing.Generic[T_co]): __slots__ = () def __enter__(self): return self @abc.abstractmethod def __exit__(self, exc_type, exc_value, traceback): return None @classmethod def __subclasshook__(cls, C): if cls is ContextManager: # In Python 3.6+, it is possible to set a method to None to # explicitly indicate that the class does not implement an ABC # (https://bugs.python.org/issue25958), but we do not support # that pattern here because this fallback class is only used # in Python 3.5 and earlier. if (any("__enter__" in B.__dict__ for B in C.__mro__) and any("__exit__" in B.__dict__ for B in C.__mro__)): return True return NotImplemented def IntVar(name): return TypeVar(name) def _is_dunder(name): """Returns True if name is a __dunder_variable_name__.""" return len(name) > 4 and name.startswith('__') and name.endswith('__') class AnnotatedMeta(GenericMeta): """Metaclass for Annotated""" def __new__(cls, name, bases, namespace, **kwargs): if any(b is not object for b in bases): raise TypeError("Cannot subclass %s" % Annotated) return super(AnnotatedMeta, cls).__new__(cls, name, bases, namespace, **kwargs) @property def __metadata__(self): return self._subs_tree()[2] def _tree_repr(self, tree): cls, origin, metadata = tree if not isinstance(origin, tuple): tp_repr = typing._type_repr(origin) else: tp_repr = origin[0]._tree_repr(origin) metadata_reprs = ", ".join(repr(arg) for arg in metadata) return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs) def _subs_tree(self, tvars=None, args=None): if self is Annotated: return Annotated res = super(AnnotatedMeta, self)._subs_tree(tvars=tvars, args=args) # Flatten nested Annotated if isinstance(res[1], tuple) and res[1][0] is Annotated: sub_tp = res[1][1] sub_annot = res[1][2] return (Annotated, sub_tp, sub_annot + res[2]) return res def _get_cons(self): """Return the class used to create instance of this type.""" if self.__origin__ is None: raise TypeError("Cannot get the underlying type of a non-specialized " "Annotated type.") tree = self._subs_tree() while isinstance(tree, tuple) and tree[0] is Annotated: tree = tree[1] if isinstance(tree, tuple): return tree[0] else: return tree @_tp_cache def __getitem__(self, params): if not isinstance(params, tuple): params = (params,) if self.__origin__ is not None: # specializing an instantiated type return super(AnnotatedMeta, self).__getitem__(params) elif not isinstance(params, tuple) or len(params) < 2: raise TypeError("Annotated[...] should be instantiated with at " "least two arguments (a type and an annotation).") else: msg = "Annotated[t, ...]: t must be a type." tp = typing._type_check(params[0], msg) metadata = tuple(params[1:]) return self.__class__( self.__name__, self.__bases__, dict(self.__dict__), tvars=_type_vars((tp,)), # Metadata is a tuple so it won't be touched by _replace_args et al. args=(tp, metadata), origin=self, ) def __call__(self, *args, **kwargs): cons = self._get_cons() result = cons(*args, **kwargs) try: result.__orig_class__ = self except AttributeError: pass return result def __getattr__(self, attr): # For simplicity we just don't relay all dunder names if self.__origin__ is not None and not _is_dunder(attr): return getattr(self._get_cons(), attr) raise AttributeError(attr) def __setattr__(self, attr, value): if _is_dunder(attr) or attr.startswith('_abc_'): super(AnnotatedMeta, self).__setattr__(attr, value) elif self.__origin__ is None: raise AttributeError(attr) else: setattr(self._get_cons(), attr, value) class Annotated(object): """Add context specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type, the remaining arguments are kept as a tuple in the __metadata__ field. Details: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: Annotated[Annotated[int, Ann1, Ann2], Ann3] == Annotated[int, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()] """ __metaclass__ = AnnotatedMeta __slots__ = () # This alias exists for backwards compatibility. runtime = runtime_checkable typing_extensions-3.7.4.1/src_py2/test_typing_extensions.py0000644000175000017500000003240713523611432024162 0ustar ivanivan00000000000000import sys import os import contextlib import collections import subprocess from unittest import TestCase, main from typing_extensions import Annotated, NoReturn, ClassVar, IntVar from typing_extensions import ContextManager, Counter, Deque, DefaultDict from typing_extensions import NewType, overload from typing import Dict, List import typing import typing_extensions T = typing.TypeVar('T') KT = typing.TypeVar('KT') VT = typing.TypeVar('VT') class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): message = '%r is not a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): if issubclass(cls, class_or_tuple): message = '%r is a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) class Employee(object): pass class NoReturnTests(BaseTestCase): def test_noreturn_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, NoReturn) def test_noreturn_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, NoReturn) with self.assertRaises(TypeError): issubclass(NoReturn, Employee) def test_repr(self): if hasattr(typing, 'NoReturn'): self.assertEqual(repr(NoReturn), 'typing.NoReturn') else: self.assertEqual(repr(NoReturn), 'typing_extensions.NoReturn') def test_not_generic(self): with self.assertRaises(TypeError): NoReturn[int] def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(NoReturn): pass with self.assertRaises(TypeError): class A(type(NoReturn)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): NoReturn() with self.assertRaises(TypeError): type(NoReturn)() class ClassVarTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): ClassVar[1] with self.assertRaises(TypeError): ClassVar[int, str] with self.assertRaises(TypeError): ClassVar[int][str] def test_repr(self): self.assertEqual(repr(ClassVar), 'typing.ClassVar') cv = ClassVar[int] self.assertEqual(repr(cv), 'typing.ClassVar[int]') cv = ClassVar[Employee] self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(ClassVar)): pass with self.assertRaises(TypeError): class C(type(ClassVar[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): ClassVar() with self.assertRaises(TypeError): type(ClassVar)() with self.assertRaises(TypeError): type(ClassVar[typing.Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, ClassVar[int]) with self.assertRaises(TypeError): issubclass(int, ClassVar) class IntVarTests(BaseTestCase): def test_valid(self): T_ints = IntVar("T_ints") # noqa def test_invalid(self): with self.assertRaises(TypeError): T_ints = IntVar("T_ints", int) with self.assertRaises(TypeError): T_ints = IntVar("T_ints", bound=int) with self.assertRaises(TypeError): T_ints = IntVar("T_ints", covariant=True) # noqa class CollectionsAbcTests(BaseTestCase): def test_isinstance_collections(self): self.assertNotIsInstance(1, collections.Mapping) self.assertNotIsInstance(1, collections.Iterable) self.assertNotIsInstance(1, collections.Container) self.assertNotIsInstance(1, collections.Sized) with self.assertRaises(TypeError): isinstance(collections.deque(), typing_extensions.Deque[int]) with self.assertRaises(TypeError): issubclass(collections.Counter, typing_extensions.Counter[str]) def test_contextmanager(self): @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertIsInstance(cm, ContextManager) self.assertNotIsInstance(42, ContextManager) with self.assertRaises(TypeError): isinstance(42, ContextManager[int]) with self.assertRaises(TypeError): isinstance(cm, ContextManager[int]) with self.assertRaises(TypeError): issubclass(type(cm), ContextManager[int]) def test_counter(self): self.assertIsSubclass(collections.Counter, Counter) self.assertIs(type(Counter()), collections.Counter) self.assertIs(type(Counter[T]()), collections.Counter) self.assertIs(type(Counter[int]()), collections.Counter) class A(Counter[int]): pass class B(Counter[T]): pass self.assertIsInstance(A(), collections.Counter) self.assertIs(type(B[int]()), B) self.assertEqual(B.__bases__, (typing_extensions.Counter,)) def test_deque(self): self.assertIsSubclass(collections.deque, Deque) self.assertIs(type(Deque()), collections.deque) self.assertIs(type(Deque[T]()), collections.deque) self.assertIs(type(Deque[int]()), collections.deque) class A(Deque[int]): pass class B(Deque[T]): pass self.assertIsInstance(A(), collections.deque) self.assertIs(type(B[int]()), B) def test_defaultdict_instantiation(self): self.assertIsSubclass(collections.defaultdict, DefaultDict) self.assertIs(type(DefaultDict()), collections.defaultdict) self.assertIs(type(DefaultDict[KT, VT]()), collections.defaultdict) self.assertIs(type(DefaultDict[str, int]()), collections.defaultdict) class A(DefaultDict[str, int]): pass class B(DefaultDict[KT, VT]): pass self.assertIsInstance(A(), collections.defaultdict) self.assertIs(type(B[str, int]()), B) class NewTypeTests(BaseTestCase): def test_basic(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) self.assertIsInstance(UserId(5), int) self.assertIsInstance(UserName('Joe'), type('Joe')) self.assertEqual(UserId(5) + 1, 6) def test_errors(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) with self.assertRaises(TypeError): issubclass(UserId, int) with self.assertRaises(TypeError): class D(UserName): pass class OverloadTests(BaseTestCase): def test_overload_fails(self): with self.assertRaises(RuntimeError): @overload def blah(): pass blah() def test_overload_succeeds(self): @overload def blah(): pass def blah(): pass blah() class AnnotatedTests(BaseTestCase): def test_repr(self): self.assertEqual( repr(Annotated[int, 4, 5]), "typing_extensions.Annotated[int, 4, 5]" ) self.assertEqual( repr(Annotated[List[int], 4, 5]), "typing_extensions.Annotated[typing.List[int], 4, 5]" ) self.assertEqual(repr(Annotated), "typing_extensions.Annotated") def test_flatten(self): A = Annotated[Annotated[int, 4], 5] self.assertEqual(A, Annotated[int, 4, 5]) self.assertEqual(A.__metadata__, (4, 5)) def test_specialize(self): L = Annotated[List[T], "my decoration"] LI = Annotated[List[int], "my decoration"] self.assertEqual(L[int], Annotated[List[int], "my decoration"]) self.assertEqual(L[int].__metadata__, ("my decoration",)) with self.assertRaises(TypeError): LI[int] with self.assertRaises(TypeError): L[int, float] def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_instantiate(self): class C: classvar = 4 def __init__(self, x): self.x = x def __eq__(self, other): if not isinstance(other, C): return NotImplemented return other.x == self.x A = Annotated[C, "a decoration"] a = A(5) c = C(5) self.assertEqual(a, c) self.assertEqual(a.x, c.x) self.assertEqual(a.classvar, c.classvar) def test_instantiate_generic(self): MyCount = Annotated[typing_extensions.Counter[T], "my decoration"] self.assertEqual(MyCount([4, 4, 5]), {4: 2, 5: 1}) self.assertEqual(MyCount[int]([4, 4, 5]), {4: 2, 5: 1}) def test_cannot_instantiate_forward(self): A = Annotated["int", (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_instantiate_type_var(self): A = Annotated[T, (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_getattr_typevar(self): with self.assertRaises(AttributeError): Annotated[T, (5, 7)].x def test_attr_passthrough(self): class C: classvar = 4 A = Annotated[C, "a decoration"] self.assertEqual(A.classvar, 4) A.x = 5 self.assertEqual(C.x, 5) def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(Annotated): pass def test_cannot_check_instance(self): with self.assertRaises(TypeError): isinstance(5, Annotated[int, "positive"]) def test_cannot_check_subclass(self): with self.assertRaises(TypeError): issubclass(int, Annotated[int, "positive"]) def test_subst(self): dec = "a decoration" dec2 = "another decoration" S = Annotated[T, dec2] self.assertEqual(S[int], Annotated[int, dec2]) self.assertEqual(S[Annotated[int, dec]], Annotated[int, dec, dec2]) L = Annotated[List[T], dec] self.assertEqual(L[int], Annotated[List[int], dec]) with self.assertRaises(TypeError): L[int, int] self.assertEqual(S[L[int]], Annotated[List[int], dec, dec2]) D = Annotated[Dict[KT, VT], dec] self.assertEqual(D[str, int], Annotated[Dict[str, int], dec]) with self.assertRaises(TypeError): D[int] It = Annotated[int, dec] with self.assertRaises(TypeError): It[None] LI = L[int] with self.assertRaises(TypeError): LI[None] def test_annotated_in_other_types(self): X = List[Annotated[T, 5]] self.assertEqual(X[int], List[Annotated[int, 5]]) class AllTests(BaseTestCase): def test_typing_extensions_includes_standard(self): a = typing_extensions.__all__ self.assertIn('ClassVar', a) self.assertIn('Type', a) self.assertIn('Counter', a) self.assertIn('DefaultDict', a) self.assertIn('Deque', a) self.assertIn('NewType', a) self.assertIn('overload', a) self.assertIn('Text', a) self.assertIn('TYPE_CHECKING', a) def test_typing_extensions_defers_when_possible(self): exclude = {'overload', 'Text', 'TYPE_CHECKING', 'Final'} for item in typing_extensions.__all__: if item not in exclude and hasattr(typing, item): self.assertIs( getattr(typing_extensions, item), getattr(typing, item)) def test_typing_extensions_compiles_with_opt(self): file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'typing_extensions.py') try: subprocess.check_output('{} -OO {}'.format(sys.executable, file_path), stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError: self.fail('Module does not compile with optimize=2 (-OO flag).') if __name__ == '__main__': main() typing_extensions-3.7.4.1/LICENSE0000644000175000017500000003072313501305176016404 0ustar ivanivan00000000000000A. HISTORY OF THE SOFTWARE ========================== Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, see http://www.zope.com). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2 and above 2.1.1 2001-now PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ------------------------------------------- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 --------------------------------------- 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013". 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 -------------------------------------------------- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. typing_extensions-3.7.4.1/README.rst0000644000175000017500000000504313555564640017077 0ustar ivanivan00000000000000================= Typing Extensions ================= .. image:: https://badges.gitter.im/python/typing.svg :alt: Chat at https://gitter.im/python/typing :target: https://gitter.im/python/typing?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge Overview ======== The ``typing`` module was added to the standard library in Python 3.5 on a provisional basis and will no longer be provisional in Python 3.7. However, this means users of Python 3.5 - 3.6 who are unable to upgrade will not be able to take advantage of new types added to the ``typing`` module, such as ``typing.Text`` or ``typing.Coroutine``. The ``typing_extensions`` module contains both backports of these changes as well as experimental types that will eventually be added to the ``typing`` module, such as ``Protocol`` (see PEP 544 for details about protocols and static duck typing) or ``TypedDict`` (see PEP 589). Users of other Python versions should continue to install and use use the ``typing`` module from PyPi instead of using this one unless specifically writing code that must be compatible with multiple Python versions or requires experimental types. Included items ============== This module currently contains the following: All Python versions: -------------------- - ``ClassVar`` - ``ContextManager`` - ``Counter`` - ``DefaultDict`` - ``Deque`` - ``final`` - ``Final`` - ``Literal`` - ``NewType`` - ``NoReturn`` - ``overload`` (note that older versions of ``typing`` only let you use ``overload`` in stubs) - ``Protocol`` (except on Python 3.5.0) - ``runtime`` (except on Python 3.5.0) - ``Text`` - ``Type`` - ``TypedDict`` - ``TYPE_CHECKING`` Python 3.4+ only: ----------------- - ``ChainMap`` Python 3.5+ only: ----------------- - ``AsyncIterable`` - ``AsyncIterator`` - ``AsyncContextManager`` - ``Awaitable`` - ``Coroutine`` Python 3.6+ only: ----------------- - ``AsyncGenerator`` Other Notes and Limitations =========================== There are a few types whose interface was modified between different versions of typing. For example, ``typing.Sequence`` was modified to subclass ``typing.Reversible`` as of Python 3.5.3. These changes are _not_ backported to prevent subtle compatibility issues when mixing the differing implementations of modified classes. Running tests ============= To run tests, navigate into the appropriate source directory and run ``test_typing_extensions.py``. You will also need to install the latest version of ``typing`` if you are using a version of Python that does not include ``typing`` as a part of the standard library. typing_extensions-3.7.4.1/MANIFEST.in0000644000175000017500000000027113501305176017130 0ustar ivanivan00000000000000include LICENSE README.rst include src_py3/typing_extensions.py include src_py3/test_typing_extensions.py include src_py2/typing_extensions.py include src_py2/test_typing_extensions.py