cpython: 294525aac5eb (original) (raw)
--- a/Lib/typing.py +++ b/Lib/typing.py @@ -100,16 +100,16 @@ def _trim_name(nm): class TypingMeta(type):
This overrides new() to require an extra keyword parameter '_root', which serves as a guard against naive subclassing of the typing classes. Any legitimate class defined using a metaclass
- derived from TypingMeta (including internal subclasses created by
- e.g. Union[X, Y]) must pass _root=True.
- This also defines a dummy constructor (all the work for most typing
- constructs is done in new) and a nicer repr(). """ _is_protocol = False @@ -126,8 +126,8 @@ class TypingMeta(type): def _eval_type(self, globalns, localns): """Override this in subclasses to interpret forward references.
For example, Union['C'] is internally stored as[](#l1.30)
Union[_ForwardRef('C')], which should evaluate to _Union[C],[](#l1.31)
For example, List['C'] is internally stored as[](#l1.32)
List[_ForwardRef('C')], which should evaluate to List[C],[](#l1.33) where C is an object found in globalns or localns (searching[](#l1.34) localns first, of course).[](#l1.35) """[](#l1.36)
@@ -142,7 +142,7 @@ class TypingMeta(type): class _TypingBase(metaclass=TypingMeta, _root=True):
slots = () @@ -179,10 +179,10 @@ class _TypingBase(metaclass=TypingMeta, class _FinalTypingBase(_TypingBase, _root=True):
Prevents instantiation unless _root=True is given in class call.
- It is used to create pseudo-singleton instances Any, Union, Optional, etc. """ slots = () @@ -198,7 +198,7 @@ class _FinalTypingBase(_TypingBase, _roo class _ForwardRef(_TypingBase, _root=True):
slots = ('forward_arg', 'forward_code', 'forward_evaluated', 'forward_value') @@ -206,11 +206,11 @@ class _ForwardRef(_TypingBase, _root=Tru def init(self, arg): super().init(arg) if not isinstance(arg, str):
raise TypeError('ForwardRef must be a string -- got %r' % (arg,))[](#l1.72)
raise TypeError('Forward reference must be a string -- got %r' % (arg,))[](#l1.73) try:[](#l1.74) code = compile(arg, '<string>', 'eval')[](#l1.75) except SyntaxError:[](#l1.76)
raise SyntaxError('ForwardRef must be an expression -- got %r' %[](#l1.77)
raise SyntaxError('Forward reference must be an expression -- got %r' %[](#l1.78) (arg,))[](#l1.79) self.__forward_arg__ = arg[](#l1.80) self.__forward_code__ = code[](#l1.81)
@@ -336,7 +336,7 @@ def _eval_type(t, globalns, localns): def _type_check(arg, msg):
As a special case, accept None and return type(None) instead. Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable. @@ -363,7 +363,7 @@ def _type_check(arg, msg): def _type_repr(obj):
If obj is a type, we return a shorter version than the default type.repr, based on the module and qualified name, which is @@ -418,7 +418,7 @@ class TypeVar(_TypingBase, _root=True): as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:
def repeat(x: T, n: int) -> Sequence[T]:[](#l1.104)
def repeat(x: T, n: int) -> List[T]:[](#l1.105) '''Return a list containing n references to x.'''[](#l1.106) return [x]*n[](#l1.107)
@@ -431,10 +431,7 @@ class TypeVar(_TypingBase, _root=True): that if the arguments are instances of some subclass of str, the return type is still plain str.
- At runtime, isinstance(x, T) will raise TypeError. However,
- issubclass(C, T) is true for any class C, and issubclass(str, A)
- and issubclass(bytes, A) are true, and issubclass(int, A) is
- false. (TODO: Why is this needed? This may change. See #136.)
Type variables defined with covariant=True or contravariant=True can be used do declare covariant or contravariant generic types. @@ -509,7 +506,7 @@ AnyStr = TypeVar('AnyStr', bytes, str) def _replace_arg(arg, tvars, args):
- """An internal helper function: replace arg if it is a type variable found in tvars with corresponding substitution from args or with corresponding substitution sub-tree if arg is a generic type. """ @@ -526,9 +523,15 @@ def _replace_arg(arg, tvars, args): def _subs_tree(cls, tvars=None, args=None):
- """ Calculate substitution tree for generic cls after
- replacing its type parameters with substitutions in tvars -> args (if any).
- Repeat the same cyclicaly following origin's.
- """An internal helper function: calculate substitution tree
- for generic cls after replacing its type parameters with
- substitutions in tvars -> args (if any).
- Repeat the same following origin's.
- Return a list of arguments with all possible substitutions
- performed. Arguments that are generic classes themselves are represented
- as tuples (so that no new classes are created by this function).
- For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)] """ if cls.origin is None: @@ -553,7 +556,7 @@ def _subs_tree(cls, tvars=None, args=Non def _remove_dups_flatten(parameters):
- """An internal helper for Union creation and substitution: flatten Union's among parameters, then remove duplicates and strict subclasses. """ @@ -594,7 +597,7 @@ def _remove_dups_flatten(parameters): def _check_generic(cls, parameters):
if not cls.parameters: Check correct count for parameters of a generic cls (internal helper). raise TypeError("%s is not a generic class" % repr(cls)) alen = len(parameters) @@ -608,7 +611,7 @@ def _check_generic(cls, parameters): def _tp_cache(func):
- """Internal wrapper caching getitem of generic types with a fallback to original function for non-hashable arguments. """ @@ -788,7 +791,7 @@ Optional = _Optional(_root=True) def _gorg(a):
- """Return the farthest origin of a generic class (internal helper).""" assert isinstance(a, GenericMeta) while a.origin is not None: a = a.origin
@@ -796,10 +799,10 @@ def _gorg(a): def _geqv(a, b):
The intention is to consider generic class X and any of its
However, X is not equivalent to a subclass of X. @@ -825,6 +828,7 @@ def _next_in_mro(cls): def _valid_for_check(cls):
- """An internal helper to prohibit isinstance([1], List[str]) etc.""" if cls is Generic: raise TypeError("Class %r cannot be used with class " "or instance checks" % cls)
@@ -1083,8 +1087,8 @@ def _generic_new(base_cls, cls, *args, * class Generic(metaclass=GenericMeta): """Abstract base class for generic types.
- A generic type is typically declared by inheriting from an
- instantiation of this class with one or more type variables.
- A generic type is typically declared by inheriting from
- this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): @@ -1111,18 +1115,18 @@ class Generic(metaclass=GenericMeta): class _TypingEmpty:
- """Placeholder for () or []. Used by TupleMeta and CallableMeta
- to allow empy list/tuple in specific places, without allowing them
- """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
- to allow empty list/tuple in specific places, without allowing them to sneak in where prohibited. """ class _TypingEllipsis:
@_tp_cache def getitem(self, parameters): @@ -1175,7 +1179,7 @@ class Tuple(tuple, extra=tuple, metaclas class CallableMeta(GenericMeta):
def repr(self): if self.origin is None: @@ -1199,7 +1203,7 @@ class CallableMeta(GenericMeta): '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1])) def getitem(self, parameters):
""" A thin wrapper around __getitem_inner__ to provide the latter[](#l1.253)
"""A thin wrapper around __getitem_inner__ to provide the latter[](#l1.254) with hashable arguments to improve speed.[](#l1.255) """[](#l1.256)
@@ -1236,7 +1240,7 @@ class Callable(extra=collections_abc.Cal The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list
There is no syntax to indicate optional or keyword arguments, such function types are rarely used as callback types. @@ -1565,7 +1569,7 @@ class _ProtocolMeta(GenericMeta): class _Protocol(metaclass=_ProtocolMeta): """Internal base class for protocol classes.