ยปCore Development>Code coverage>Lib/typing.py

Python code coverage for Lib/typing.py

#countcontent
1n/aimport abc
2n/afrom abc import abstractmethod, abstractproperty
3n/aimport collections
4n/aimport contextlib
5n/aimport functools
6n/aimport re as stdlib_re # Avoid confusion with the re we export.
7n/aimport sys
8n/aimport types
9n/atry:
10n/a import collections.abc as collections_abc
11n/aexcept ImportError:
12n/a import collections as collections_abc # Fallback for PY3.2.
13n/a
14n/a
15n/a# Please keep __all__ alphabetized within each category.
16n/a__all__ = [
17n/a # Super-special typing primitives.
18n/a 'Any',
19n/a 'Callable',
20n/a 'ClassVar',
21n/a 'Generic',
22n/a 'Optional',
23n/a 'Tuple',
24n/a 'Type',
25n/a 'TypeVar',
26n/a 'Union',
27n/a
28n/a # ABCs (from collections.abc).
29n/a 'AbstractSet', # collections.abc.Set.
30n/a 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
31n/a # for 'Generic' and ABCs below.
32n/a 'ByteString',
33n/a 'Container',
34n/a 'Hashable',
35n/a 'ItemsView',
36n/a 'Iterable',
37n/a 'Iterator',
38n/a 'KeysView',
39n/a 'Mapping',
40n/a 'MappingView',
41n/a 'MutableMapping',
42n/a 'MutableSequence',
43n/a 'MutableSet',
44n/a 'Sequence',
45n/a 'Sized',
46n/a 'ValuesView',
47n/a # The following are added depending on presence
48n/a # of their non-generic counterparts in stdlib:
49n/a # Awaitable,
50n/a # AsyncIterator,
51n/a # AsyncIterable,
52n/a # Coroutine,
53n/a # Collection,
54n/a # ContextManager,
55n/a # AsyncGenerator,
56n/a
57n/a # Structural checks, a.k.a. protocols.
58n/a 'Reversible',
59n/a 'SupportsAbs',
60n/a 'SupportsFloat',
61n/a 'SupportsInt',
62n/a 'SupportsRound',
63n/a
64n/a # Concrete collection types.
65n/a 'Deque',
66n/a 'Dict',
67n/a 'DefaultDict',
68n/a 'List',
69n/a 'Set',
70n/a 'FrozenSet',
71n/a 'NamedTuple', # Not really a type.
72n/a 'Generator',
73n/a
74n/a # One-off things.
75n/a 'AnyStr',
76n/a 'cast',
77n/a 'get_type_hints',
78n/a 'NewType',
79n/a 'no_type_check',
80n/a 'no_type_check_decorator',
81n/a 'overload',
82n/a 'Text',
83n/a 'TYPE_CHECKING',
84n/a]
85n/a
86n/a# The pseudo-submodules 're' and 'io' are part of the public
87n/a# namespace, but excluded from __all__ because they might stomp on
88n/a# legitimate imports of those modules.
89n/a
90n/a
91n/adef _qualname(x):
92n/a if sys.version_info[:2] >= (3, 3):
93n/a return x.__qualname__
94n/a else:
95n/a # Fall back to just name.
96n/a return x.__name__
97n/a
98n/a
99n/adef _trim_name(nm):
100n/a whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
101n/a if nm.startswith('_') and nm not in whitelist:
102n/a nm = nm[1:]
103n/a return nm
104n/a
105n/a
106n/aclass TypingMeta(type):
107n/a """Metaclass for most types defined in typing module
108n/a (not a part of public API).
109n/a
110n/a This overrides __new__() to require an extra keyword parameter
111n/a '_root', which serves as a guard against naive subclassing of the
112n/a typing classes. Any legitimate class defined using a metaclass
113n/a derived from TypingMeta must pass _root=True.
114n/a
115n/a This also defines a dummy constructor (all the work for most typing
116n/a constructs is done in __new__) and a nicer repr().
117n/a """
118n/a
119n/a _is_protocol = False
120n/a
121n/a def __new__(cls, name, bases, namespace, *, _root=False):
122n/a if not _root:
123n/a raise TypeError("Cannot subclass %s" %
124n/a (', '.join(map(_type_repr, bases)) or '()'))
125n/a return super().__new__(cls, name, bases, namespace)
126n/a
127n/a def __init__(self, *args, **kwds):
128n/a pass
129n/a
130n/a def _eval_type(self, globalns, localns):
131n/a """Override this in subclasses to interpret forward references.
132n/a
133n/a For example, List['C'] is internally stored as
134n/a List[_ForwardRef('C')], which should evaluate to List[C],
135n/a where C is an object found in globalns or localns (searching
136n/a localns first, of course).
137n/a """
138n/a return self
139n/a
140n/a def _get_type_vars(self, tvars):
141n/a pass
142n/a
143n/a def __repr__(self):
144n/a qname = _trim_name(_qualname(self))
145n/a return '%s.%s' % (self.__module__, qname)
146n/a
147n/a
148n/aclass _TypingBase(metaclass=TypingMeta, _root=True):
149n/a """Internal indicator of special typing constructs."""
150n/a
151n/a __slots__ = ('__weakref__',)
152n/a
153n/a def __init__(self, *args, **kwds):
154n/a pass
155n/a
156n/a def __new__(cls, *args, **kwds):
157n/a """Constructor.
158n/a
159n/a This only exists to give a better error message in case
160n/a someone tries to subclass a special typing object (not a good idea).
161n/a """
162n/a if (len(args) == 3 and
163n/a isinstance(args[0], str) and
164n/a isinstance(args[1], tuple)):
165n/a # Close enough.
166n/a raise TypeError("Cannot subclass %r" % cls)
167n/a return super().__new__(cls)
168n/a
169n/a # Things that are not classes also need these.
170n/a def _eval_type(self, globalns, localns):
171n/a return self
172n/a
173n/a def _get_type_vars(self, tvars):
174n/a pass
175n/a
176n/a def __repr__(self):
177n/a cls = type(self)
178n/a qname = _trim_name(_qualname(cls))
179n/a return '%s.%s' % (cls.__module__, qname)
180n/a
181n/a def __call__(self, *args, **kwds):
182n/a raise TypeError("Cannot instantiate %r" % type(self))
183n/a
184n/a
185n/aclass _FinalTypingBase(_TypingBase, _root=True):
186n/a """Internal mix-in class to prevent instantiation.
187n/a
188n/a Prevents instantiation unless _root=True is given in class call.
189n/a It is used to create pseudo-singleton instances Any, Union, Optional, etc.
190n/a """
191n/a
192n/a __slots__ = ()
193n/a
194n/a def __new__(cls, *args, _root=False, **kwds):
195n/a self = super().__new__(cls, *args, **kwds)
196n/a if _root is True:
197n/a return self
198n/a raise TypeError("Cannot instantiate %r" % cls)
199n/a
200n/a def __reduce__(self):
201n/a return _trim_name(type(self).__name__)
202n/a
203n/a
204n/aclass _ForwardRef(_TypingBase, _root=True):
205n/a """Internal wrapper to hold a forward reference."""
206n/a
207n/a __slots__ = ('__forward_arg__', '__forward_code__',
208n/a '__forward_evaluated__', '__forward_value__')
209n/a
210n/a def __init__(self, arg):
211n/a super().__init__(arg)
212n/a if not isinstance(arg, str):
213n/a raise TypeError('Forward reference must be a string -- got %r' % (arg,))
214n/a try:
215n/a code = compile(arg, '<string>', 'eval')
216n/a except SyntaxError:
217n/a raise SyntaxError('Forward reference must be an expression -- got %r' %
218n/a (arg,))
219n/a self.__forward_arg__ = arg
220n/a self.__forward_code__ = code
221n/a self.__forward_evaluated__ = False
222n/a self.__forward_value__ = None
223n/a
224n/a def _eval_type(self, globalns, localns):
225n/a if not self.__forward_evaluated__ or localns is not globalns:
226n/a if globalns is None and localns is None:
227n/a globalns = localns = {}
228n/a elif globalns is None:
229n/a globalns = localns
230n/a elif localns is None:
231n/a localns = globalns
232n/a self.__forward_value__ = _type_check(
233n/a eval(self.__forward_code__, globalns, localns),
234n/a "Forward references must evaluate to types.")
235n/a self.__forward_evaluated__ = True
236n/a return self.__forward_value__
237n/a
238n/a def __eq__(self, other):
239n/a if not isinstance(other, _ForwardRef):
240n/a return NotImplemented
241n/a return (self.__forward_arg__ == other.__forward_arg__ and
242n/a self.__forward_value__ == other.__forward_value__)
243n/a
244n/a def __hash__(self):
245n/a return hash((self.__forward_arg__, self.__forward_value__))
246n/a
247n/a def __instancecheck__(self, obj):
248n/a raise TypeError("Forward references cannot be used with isinstance().")
249n/a
250n/a def __subclasscheck__(self, cls):
251n/a raise TypeError("Forward references cannot be used with issubclass().")
252n/a
253n/a def __repr__(self):
254n/a return '_ForwardRef(%r)' % (self.__forward_arg__,)
255n/a
256n/a
257n/aclass _TypeAlias(_TypingBase, _root=True):
258n/a """Internal helper class for defining generic variants of concrete types.
259n/a
260n/a Note that this is not a type; let's call it a pseudo-type. It cannot
261n/a be used in instance and subclass checks in parameterized form, i.e.
262n/a ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
263n/a ``False``.
264n/a """
265n/a
266n/a __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
267n/a
268n/a def __init__(self, name, type_var, impl_type, type_checker):
269n/a """Initializer.
270n/a
271n/a Args:
272n/a name: The name, e.g. 'Pattern'.
273n/a type_var: The type parameter, e.g. AnyStr, or the
274n/a specific type, e.g. str.
275n/a impl_type: The implementation type.
276n/a type_checker: Function that takes an impl_type instance.
277n/a and returns a value that should be a type_var instance.
278n/a """
279n/a assert isinstance(name, str), repr(name)
280n/a assert isinstance(impl_type, type), repr(impl_type)
281n/a assert not isinstance(impl_type, TypingMeta), repr(impl_type)
282n/a assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
283n/a self.name = name
284n/a self.type_var = type_var
285n/a self.impl_type = impl_type
286n/a self.type_checker = type_checker
287n/a
288n/a def __repr__(self):
289n/a return "%s[%s]" % (self.name, _type_repr(self.type_var))
290n/a
291n/a def __getitem__(self, parameter):
292n/a if not isinstance(self.type_var, TypeVar):
293n/a raise TypeError("%s cannot be further parameterized." % self)
294n/a if self.type_var.__constraints__ and isinstance(parameter, type):
295n/a if not issubclass(parameter, self.type_var.__constraints__):
296n/a raise TypeError("%s is not a valid substitution for %s." %
297n/a (parameter, self.type_var))
298n/a if isinstance(parameter, TypeVar) and parameter is not self.type_var:
299n/a raise TypeError("%s cannot be re-parameterized." % self)
300n/a return self.__class__(self.name, parameter,
301n/a self.impl_type, self.type_checker)
302n/a
303n/a def __eq__(self, other):
304n/a if not isinstance(other, _TypeAlias):
305n/a return NotImplemented
306n/a return self.name == other.name and self.type_var == other.type_var
307n/a
308n/a def __hash__(self):
309n/a return hash((self.name, self.type_var))
310n/a
311n/a def __instancecheck__(self, obj):
312n/a if not isinstance(self.type_var, TypeVar):
313n/a raise TypeError("Parameterized type aliases cannot be used "
314n/a "with isinstance().")
315n/a return isinstance(obj, self.impl_type)
316n/a
317n/a def __subclasscheck__(self, cls):
318n/a if not isinstance(self.type_var, TypeVar):
319n/a raise TypeError("Parameterized type aliases cannot be used "
320n/a "with issubclass().")
321n/a return issubclass(cls, self.impl_type)
322n/a
323n/a
324n/adef _get_type_vars(types, tvars):
325n/a for t in types:
326n/a if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
327n/a t._get_type_vars(tvars)
328n/a
329n/a
330n/adef _type_vars(types):
331n/a tvars = []
332n/a _get_type_vars(types, tvars)
333n/a return tuple(tvars)
334n/a
335n/a
336n/adef _eval_type(t, globalns, localns):
337n/a if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
338n/a return t._eval_type(globalns, localns)
339n/a return t
340n/a
341n/a
342n/adef _type_check(arg, msg):
343n/a """Check that the argument is a type, and return it (internal helper).
344n/a
345n/a As a special case, accept None and return type(None) instead.
346n/a Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
347n/a
348n/a The msg argument is a human-readable error message, e.g.
349n/a
350n/a "Union[arg, ...]: arg should be a type."
351n/a
352n/a We append the repr() of the actual value (truncated to 100 chars).
353n/a """
354n/a if arg is None:
355n/a return type(None)
356n/a if isinstance(arg, str):
357n/a arg = _ForwardRef(arg)
358n/a if (
359n/a isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
360n/a not isinstance(arg, (type, _TypingBase)) and not callable(arg)
361n/a ):
362n/a raise TypeError(msg + " Got %.100r." % (arg,))
363n/a # Bare Union etc. are not valid as type arguments
364n/a if (
365n/a type(arg).__name__ in ('_Union', '_Optional') and
366n/a not getattr(arg, '__origin__', None) or
367n/a isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)
368n/a ):
369n/a raise TypeError("Plain %s is not valid as type argument" % arg)
370n/a return arg
371n/a
372n/a
373n/adef _type_repr(obj):
374n/a """Return the repr() of an object, special-casing types (internal helper).
375n/a
376n/a If obj is a type, we return a shorter version than the default
377n/a type.__repr__, based on the module and qualified name, which is
378n/a typically enough to uniquely identify a type. For everything
379n/a else, we fall back on repr(obj).
380n/a """
381n/a if isinstance(obj, type) and not isinstance(obj, TypingMeta):
382n/a if obj.__module__ == 'builtins':
383n/a return _qualname(obj)
384n/a return '%s.%s' % (obj.__module__, _qualname(obj))
385n/a if obj is ...:
386n/a return('...')
387n/a if isinstance(obj, types.FunctionType):
388n/a return obj.__name__
389n/a return repr(obj)
390n/a
391n/a
392n/aclass _Any(_FinalTypingBase, _root=True):
393n/a """Special type indicating an unconstrained type.
394n/a
395n/a - Any is compatible with every type.
396n/a - Any assumed to have all methods.
397n/a - All values assumed to be instances of Any.
398n/a
399n/a Note that all the above statements are true from the point of view of
400n/a static type checkers. At runtime, Any should not be used with instance
401n/a or class checks.
402n/a """
403n/a
404n/a __slots__ = ()
405n/a
406n/a def __instancecheck__(self, obj):
407n/a raise TypeError("Any cannot be used with isinstance().")
408n/a
409n/a def __subclasscheck__(self, cls):
410n/a raise TypeError("Any cannot be used with issubclass().")
411n/a
412n/a
413n/aAny = _Any(_root=True)
414n/a
415n/a
416n/aclass TypeVar(_TypingBase, _root=True):
417n/a """Type variable.
418n/a
419n/a Usage::
420n/a
421n/a T = TypeVar('T') # Can be anything
422n/a A = TypeVar('A', str, bytes) # Must be str or bytes
423n/a
424n/a Type variables exist primarily for the benefit of static type
425n/a checkers. They serve as the parameters for generic types as well
426n/a as for generic function definitions. See class Generic for more
427n/a information on generic types. Generic functions work as follows:
428n/a
429n/a def repeat(x: T, n: int) -> List[T]:
430n/a '''Return a list containing n references to x.'''
431n/a return [x]*n
432n/a
433n/a def longest(x: A, y: A) -> A:
434n/a '''Return the longest of two strings.'''
435n/a return x if len(x) >= len(y) else y
436n/a
437n/a The latter example's signature is essentially the overloading
438n/a of (str, str) -> str and (bytes, bytes) -> bytes. Also note
439n/a that if the arguments are instances of some subclass of str,
440n/a the return type is still plain str.
441n/a
442n/a At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
443n/a
444n/a Type variables defined with covariant=True or contravariant=True
445n/a can be used do declare covariant or contravariant generic types.
446n/a See PEP 484 for more details. By default generic types are invariant
447n/a in all type variables.
448n/a
449n/a Type variables can be introspected. e.g.:
450n/a
451n/a T.__name__ == 'T'
452n/a T.__constraints__ == ()
453n/a T.__covariant__ == False
454n/a T.__contravariant__ = False
455n/a A.__constraints__ == (str, bytes)
456n/a """
457n/a
458n/a __slots__ = ('__name__', '__bound__', '__constraints__',
459n/a '__covariant__', '__contravariant__')
460n/a
461n/a def __init__(self, name, *constraints, bound=None,
462n/a covariant=False, contravariant=False):
463n/a super().__init__(name, *constraints, bound=bound,
464n/a covariant=covariant, contravariant=contravariant)
465n/a self.__name__ = name
466n/a if covariant and contravariant:
467n/a raise ValueError("Bivariant types are not supported.")
468n/a self.__covariant__ = bool(covariant)
469n/a self.__contravariant__ = bool(contravariant)
470n/a if constraints and bound is not None:
471n/a raise TypeError("Constraints cannot be combined with bound=...")
472n/a if constraints and len(constraints) == 1:
473n/a raise TypeError("A single constraint is not allowed")
474n/a msg = "TypeVar(name, constraint, ...): constraints must be types."
475n/a self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
476n/a if bound:
477n/a self.__bound__ = _type_check(bound, "Bound must be a type.")
478n/a else:
479n/a self.__bound__ = None
480n/a
481n/a def _get_type_vars(self, tvars):
482n/a if self not in tvars:
483n/a tvars.append(self)
484n/a
485n/a def __repr__(self):
486n/a if self.__covariant__:
487n/a prefix = '+'
488n/a elif self.__contravariant__:
489n/a prefix = '-'
490n/a else:
491n/a prefix = '~'
492n/a return prefix + self.__name__
493n/a
494n/a def __instancecheck__(self, instance):
495n/a raise TypeError("Type variables cannot be used with isinstance().")
496n/a
497n/a def __subclasscheck__(self, cls):
498n/a raise TypeError("Type variables cannot be used with issubclass().")
499n/a
500n/a
501n/a# Some unconstrained type variables. These are used by the container types.
502n/a# (These are not for export.)
503n/aT = TypeVar('T') # Any type.
504n/aKT = TypeVar('KT') # Key type.
505n/aVT = TypeVar('VT') # Value type.
506n/aT_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
507n/aV_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
508n/aVT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
509n/aT_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
510n/a
511n/a# A useful type variable with constraints. This represents string types.
512n/a# (This one *is* for export!)
513n/aAnyStr = TypeVar('AnyStr', bytes, str)
514n/a
515n/a
516n/adef _replace_arg(arg, tvars, args):
517n/a """An internal helper function: replace arg if it is a type variable
518n/a found in tvars with corresponding substitution from args or
519n/a with corresponding substitution sub-tree if arg is a generic type.
520n/a """
521n/a
522n/a if tvars is None:
523n/a tvars = []
524n/a if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
525n/a return arg._subs_tree(tvars, args)
526n/a if isinstance(arg, TypeVar):
527n/a for i, tvar in enumerate(tvars):
528n/a if arg == tvar:
529n/a return args[i]
530n/a return arg
531n/a
532n/a
533n/a# Special typing constructs Union, Optional, Generic, Callable and Tuple
534n/a# use three special attributes for internal bookkeeping of generic types:
535n/a# * __parameters__ is a tuple of unique free type parameters of a generic
536n/a# type, for example, Dict[T, T].__parameters__ == (T,);
537n/a# * __origin__ keeps a reference to a type that was subscripted,
538n/a# e.g., Union[T, int].__origin__ == Union;
539n/a# * __args__ is a tuple of all arguments used in subscripting,
540n/a# e.g., Dict[T, int].__args__ == (T, int).
541n/a
542n/a
543n/adef _subs_tree(cls, tvars=None, args=None):
544n/a """An internal helper function: calculate substitution tree
545n/a for generic cls after replacing its type parameters with
546n/a substitutions in tvars -> args (if any).
547n/a Repeat the same following __origin__'s.
548n/a
549n/a Return a list of arguments with all possible substitutions
550n/a performed. Arguments that are generic classes themselves are represented
551n/a as tuples (so that no new classes are created by this function).
552n/a For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
553n/a """
554n/a
555n/a if cls.__origin__ is None:
556n/a return cls
557n/a # Make of chain of origins (i.e. cls -> cls.__origin__)
558n/a current = cls.__origin__
559n/a orig_chain = []
560n/a while current.__origin__ is not None:
561n/a orig_chain.append(current)
562n/a current = current.__origin__
563n/a # Replace type variables in __args__ if asked ...
564n/a tree_args = []
565n/a for arg in cls.__args__:
566n/a tree_args.append(_replace_arg(arg, tvars, args))
567n/a # ... then continue replacing down the origin chain.
568n/a for ocls in orig_chain:
569n/a new_tree_args = []
570n/a for arg in ocls.__args__:
571n/a new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
572n/a tree_args = new_tree_args
573n/a return tree_args
574n/a
575n/a
576n/adef _remove_dups_flatten(parameters):
577n/a """An internal helper for Union creation and substitution: flatten Union's
578n/a among parameters, then remove duplicates and strict subclasses.
579n/a """
580n/a
581n/a # Flatten out Union[Union[...], ...].
582n/a params = []
583n/a for p in parameters:
584n/a if isinstance(p, _Union) and p.__origin__ is Union:
585n/a params.extend(p.__args__)
586n/a elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
587n/a params.extend(p[1:])
588n/a else:
589n/a params.append(p)
590n/a # Weed out strict duplicates, preserving the first of each occurrence.
591n/a all_params = set(params)
592n/a if len(all_params) < len(params):
593n/a new_params = []
594n/a for t in params:
595n/a if t in all_params:
596n/a new_params.append(t)
597n/a all_params.remove(t)
598n/a params = new_params
599n/a assert not all_params, all_params
600n/a # Weed out subclasses.
601n/a # E.g. Union[int, Employee, Manager] == Union[int, Employee].
602n/a # If object is present it will be sole survivor among proper classes.
603n/a # Never discard type variables.
604n/a # (In particular, Union[str, AnyStr] != AnyStr.)
605n/a all_params = set(params)
606n/a for t1 in params:
607n/a if not isinstance(t1, type):
608n/a continue
609n/a if any(isinstance(t2, type) and issubclass(t1, t2)
610n/a for t2 in all_params - {t1}
611n/a if not (isinstance(t2, GenericMeta) and
612n/a t2.__origin__ is not None)):
613n/a all_params.remove(t1)
614n/a return tuple(t for t in params if t in all_params)
615n/a
616n/a
617n/adef _check_generic(cls, parameters):
618n/a # Check correct count for parameters of a generic cls (internal helper).
619n/a if not cls.__parameters__:
620n/a raise TypeError("%s is not a generic class" % repr(cls))
621n/a alen = len(parameters)
622n/a elen = len(cls.__parameters__)
623n/a if alen != elen:
624n/a raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
625n/a ("many" if alen > elen else "few", repr(cls), alen, elen))
626n/a
627n/a
628n/a_cleanups = []
629n/a
630n/a
631n/adef _tp_cache(func):
632n/a """Internal wrapper caching __getitem__ of generic types with a fallback to
633n/a original function for non-hashable arguments.
634n/a """
635n/a
636n/a cached = functools.lru_cache()(func)
637n/a _cleanups.append(cached.cache_clear)
638n/a
639n/a @functools.wraps(func)
640n/a def inner(*args, **kwds):
641n/a try:
642n/a return cached(*args, **kwds)
643n/a except TypeError:
644n/a pass # All real errors (not unhashable args) are raised below.
645n/a return func(*args, **kwds)
646n/a return inner
647n/a
648n/a
649n/aclass _Union(_FinalTypingBase, _root=True):
650n/a """Union type; Union[X, Y] means either X or Y.
651n/a
652n/a To define a union, use e.g. Union[int, str]. Details:
653n/a
654n/a - The arguments must be types and there must be at least one.
655n/a
656n/a - None as an argument is a special case and is replaced by
657n/a type(None).
658n/a
659n/a - Unions of unions are flattened, e.g.::
660n/a
661n/a Union[Union[int, str], float] == Union[int, str, float]
662n/a
663n/a - Unions of a single argument vanish, e.g.::
664n/a
665n/a Union[int] == int # The constructor actually returns int
666n/a
667n/a - Redundant arguments are skipped, e.g.::
668n/a
669n/a Union[int, str, int] == Union[int, str]
670n/a
671n/a - When comparing unions, the argument order is ignored, e.g.::
672n/a
673n/a Union[int, str] == Union[str, int]
674n/a
675n/a - When two arguments have a subclass relationship, the least
676n/a derived argument is kept, e.g.::
677n/a
678n/a class Employee: pass
679n/a class Manager(Employee): pass
680n/a Union[int, Employee, Manager] == Union[int, Employee]
681n/a Union[Manager, int, Employee] == Union[int, Employee]
682n/a Union[Employee, Manager] == Employee
683n/a
684n/a - Similar for object::
685n/a
686n/a Union[int, object] == object
687n/a
688n/a - You cannot subclass or instantiate a union.
689n/a
690n/a - You can use Optional[X] as a shorthand for Union[X, None].
691n/a """
692n/a
693n/a __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
694n/a
695n/a def __new__(cls, parameters=None, origin=None, *args, _root=False):
696n/a self = super().__new__(cls, parameters, origin, *args, _root=_root)
697n/a if origin is None:
698n/a self.__parameters__ = None
699n/a self.__args__ = None
700n/a self.__origin__ = None
701n/a self.__tree_hash__ = hash(frozenset(('Union',)))
702n/a return self
703n/a if not isinstance(parameters, tuple):
704n/a raise TypeError("Expected parameters=<tuple>")
705n/a if origin is Union:
706n/a parameters = _remove_dups_flatten(parameters)
707n/a # It's not a union if there's only one type left.
708n/a if len(parameters) == 1:
709n/a return parameters[0]
710n/a self.__parameters__ = _type_vars(parameters)
711n/a self.__args__ = parameters
712n/a self.__origin__ = origin
713n/a # Pre-calculate the __hash__ on instantiation.
714n/a # This improves speed for complex substitutions.
715n/a subs_tree = self._subs_tree()
716n/a if isinstance(subs_tree, tuple):
717n/a self.__tree_hash__ = hash(frozenset(subs_tree))
718n/a else:
719n/a self.__tree_hash__ = hash(subs_tree)
720n/a return self
721n/a
722n/a def _eval_type(self, globalns, localns):
723n/a if self.__args__ is None:
724n/a return self
725n/a ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
726n/a ev_origin = _eval_type(self.__origin__, globalns, localns)
727n/a if ev_args == self.__args__ and ev_origin == self.__origin__:
728n/a # Everything is already evaluated.
729n/a return self
730n/a return self.__class__(ev_args, ev_origin, _root=True)
731n/a
732n/a def _get_type_vars(self, tvars):
733n/a if self.__origin__ and self.__parameters__:
734n/a _get_type_vars(self.__parameters__, tvars)
735n/a
736n/a def __repr__(self):
737n/a if self.__origin__ is None:
738n/a return super().__repr__()
739n/a tree = self._subs_tree()
740n/a if not isinstance(tree, tuple):
741n/a return repr(tree)
742n/a return tree[0]._tree_repr(tree)
743n/a
744n/a def _tree_repr(self, tree):
745n/a arg_list = []
746n/a for arg in tree[1:]:
747n/a if not isinstance(arg, tuple):
748n/a arg_list.append(_type_repr(arg))
749n/a else:
750n/a arg_list.append(arg[0]._tree_repr(arg))
751n/a return super().__repr__() + '[%s]' % ', '.join(arg_list)
752n/a
753n/a @_tp_cache
754n/a def __getitem__(self, parameters):
755n/a if parameters == ():
756n/a raise TypeError("Cannot take a Union of no types.")
757n/a if not isinstance(parameters, tuple):
758n/a parameters = (parameters,)
759n/a if self.__origin__ is None:
760n/a msg = "Union[arg, ...]: each arg must be a type."
761n/a else:
762n/a msg = "Parameters to generic types must be types."
763n/a parameters = tuple(_type_check(p, msg) for p in parameters)
764n/a if self is not Union:
765n/a _check_generic(self, parameters)
766n/a return self.__class__(parameters, origin=self, _root=True)
767n/a
768n/a def _subs_tree(self, tvars=None, args=None):
769n/a if self is Union:
770n/a return Union # Nothing to substitute
771n/a tree_args = _subs_tree(self, tvars, args)
772n/a tree_args = _remove_dups_flatten(tree_args)
773n/a if len(tree_args) == 1:
774n/a return tree_args[0] # Union of a single type is that type
775n/a return (Union,) + tree_args
776n/a
777n/a def __eq__(self, other):
778n/a if isinstance(other, _Union):
779n/a return self.__tree_hash__ == other.__tree_hash__
780n/a elif self is not Union:
781n/a return self._subs_tree() == other
782n/a else:
783n/a return self is other
784n/a
785n/a def __hash__(self):
786n/a return self.__tree_hash__
787n/a
788n/a def __instancecheck__(self, obj):
789n/a raise TypeError("Unions cannot be used with isinstance().")
790n/a
791n/a def __subclasscheck__(self, cls):
792n/a raise TypeError("Unions cannot be used with issubclass().")
793n/a
794n/a
795n/aUnion = _Union(_root=True)
796n/a
797n/a
798n/aclass _Optional(_FinalTypingBase, _root=True):
799n/a """Optional type.
800n/a
801n/a Optional[X] is equivalent to Union[X, None].
802n/a """
803n/a
804n/a __slots__ = ()
805n/a
806n/a @_tp_cache
807n/a def __getitem__(self, arg):
808n/a arg = _type_check(arg, "Optional[t] requires a single type.")
809n/a return Union[arg, type(None)]
810n/a
811n/a
812n/aOptional = _Optional(_root=True)
813n/a
814n/a
815n/adef _gorg(a):
816n/a """Return the farthest origin of a generic class (internal helper)."""
817n/a assert isinstance(a, GenericMeta)
818n/a while a.__origin__ is not None:
819n/a a = a.__origin__
820n/a return a
821n/a
822n/a
823n/adef _geqv(a, b):
824n/a """Return whether two generic classes are equivalent (internal helper).
825n/a
826n/a The intention is to consider generic class X and any of its
827n/a parameterized forms (X[T], X[int], etc.) as equivalent.
828n/a
829n/a However, X is not equivalent to a subclass of X.
830n/a
831n/a The relation is reflexive, symmetric and transitive.
832n/a """
833n/a assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
834n/a # Reduce each to its origin.
835n/a return _gorg(a) is _gorg(b)
836n/a
837n/a
838n/adef _next_in_mro(cls):
839n/a """Helper for Generic.__new__.
840n/a
841n/a Returns the class after the last occurrence of Generic or
842n/a Generic[...] in cls.__mro__.
843n/a """
844n/a next_in_mro = object
845n/a # Look for the last occurrence of Generic or Generic[...].
846n/a for i, c in enumerate(cls.__mro__[:-1]):
847n/a if isinstance(c, GenericMeta) and _gorg(c) is Generic:
848n/a next_in_mro = cls.__mro__[i + 1]
849n/a return next_in_mro
850n/a
851n/a
852n/adef _valid_for_check(cls):
853n/a """An internal helper to prohibit isinstance([1], List[str]) etc."""
854n/a if cls is Generic:
855n/a raise TypeError("Class %r cannot be used with class "
856n/a "or instance checks" % cls)
857n/a if (
858n/a cls.__origin__ is not None and
859n/a sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']
860n/a ):
861n/a raise TypeError("Parameterized generics cannot be used with class "
862n/a "or instance checks")
863n/a
864n/a
865n/adef _make_subclasshook(cls):
866n/a """Construct a __subclasshook__ callable that incorporates
867n/a the associated __extra__ class in subclass checks performed
868n/a against cls.
869n/a """
870n/a if isinstance(cls.__extra__, abc.ABCMeta):
871n/a # The logic mirrors that of ABCMeta.__subclasscheck__.
872n/a # Registered classes need not be checked here because
873n/a # cls and its extra share the same _abc_registry.
874n/a def __extrahook__(subclass):
875n/a _valid_for_check(cls)
876n/a res = cls.__extra__.__subclasshook__(subclass)
877n/a if res is not NotImplemented:
878n/a return res
879n/a if cls.__extra__ in subclass.__mro__:
880n/a return True
881n/a for scls in cls.__extra__.__subclasses__():
882n/a if isinstance(scls, GenericMeta):
883n/a continue
884n/a if issubclass(subclass, scls):
885n/a return True
886n/a return NotImplemented
887n/a else:
888n/a # For non-ABC extras we'll just call issubclass().
889n/a def __extrahook__(subclass):
890n/a _valid_for_check(cls)
891n/a if cls.__extra__ and issubclass(subclass, cls.__extra__):
892n/a return True
893n/a return NotImplemented
894n/a return __extrahook__
895n/a
896n/a
897n/adef _no_slots_copy(dct):
898n/a """Internal helper: copy class __dict__ and clean slots class variables.
899n/a (They will be re-created if necessary by normal class machinery.)
900n/a """
901n/a dict_copy = dict(dct)
902n/a if '__slots__' in dict_copy:
903n/a for slot in dict_copy['__slots__']:
904n/a dict_copy.pop(slot, None)
905n/a return dict_copy
906n/a
907n/a
908n/aclass GenericMeta(TypingMeta, abc.ABCMeta):
909n/a """Metaclass for generic types.
910n/a
911n/a This is a metaclass for typing.Generic and generic ABCs defined in
912n/a typing module. User defined subclasses of GenericMeta can override
913n/a __new__ and invoke super().__new__. Note that GenericMeta.__new__
914n/a has strict rules on what is allowed in its bases argument:
915n/a * plain Generic is disallowed in bases;
916n/a * Generic[...] should appear in bases at most once;
917n/a * if Generic[...] is present, then it should list all type variables
918n/a that appear in other bases.
919n/a In addition, type of all generic bases is erased, e.g., C[int] is
920n/a stripped to plain C.
921n/a """
922n/a
923n/a def __new__(cls, name, bases, namespace,
924n/a tvars=None, args=None, origin=None, extra=None, orig_bases=None):
925n/a """Create a new generic class. GenericMeta.__new__ accepts
926n/a keyword arguments that are used for internal bookkeeping, therefore
927n/a an override should pass unused keyword arguments to super().
928n/a """
929n/a if tvars is not None:
930n/a # Called from __getitem__() below.
931n/a assert origin is not None
932n/a assert all(isinstance(t, TypeVar) for t in tvars), tvars
933n/a else:
934n/a # Called from class statement.
935n/a assert tvars is None, tvars
936n/a assert args is None, args
937n/a assert origin is None, origin
938n/a
939n/a # Get the full set of tvars from the bases.
940n/a tvars = _type_vars(bases)
941n/a # Look for Generic[T1, ..., Tn].
942n/a # If found, tvars must be a subset of it.
943n/a # If not found, tvars is it.
944n/a # Also check for and reject plain Generic,
945n/a # and reject multiple Generic[...].
946n/a gvars = None
947n/a for base in bases:
948n/a if base is Generic:
949n/a raise TypeError("Cannot inherit from plain Generic")
950n/a if (isinstance(base, GenericMeta) and
951n/a base.__origin__ is Generic):
952n/a if gvars is not None:
953n/a raise TypeError(
954n/a "Cannot inherit from Generic[...] multiple types.")
955n/a gvars = base.__parameters__
956n/a if gvars is None:
957n/a gvars = tvars
958n/a else:
959n/a tvarset = set(tvars)
960n/a gvarset = set(gvars)
961n/a if not tvarset <= gvarset:
962n/a raise TypeError(
963n/a "Some type variables (%s) "
964n/a "are not listed in Generic[%s]" %
965n/a (", ".join(str(t) for t in tvars if t not in gvarset),
966n/a ", ".join(str(g) for g in gvars)))
967n/a tvars = gvars
968n/a
969n/a initial_bases = bases
970n/a if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
971n/a bases = (extra,) + bases
972n/a bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
973n/a
974n/a # remove bare Generic from bases if there are other generic bases
975n/a if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
976n/a bases = tuple(b for b in bases if b is not Generic)
977n/a self = super().__new__(cls, name, bases, namespace, _root=True)
978n/a
979n/a self.__parameters__ = tvars
980n/a # Be prepared that GenericMeta will be subclassed by TupleMeta
981n/a # and CallableMeta, those two allow ..., (), or [] in __args___.
982n/a self.__args__ = tuple(... if a is _TypingEllipsis else
983n/a () if a is _TypingEmpty else
984n/a a for a in args) if args else None
985n/a self.__origin__ = origin
986n/a self.__extra__ = extra
987n/a # Speed hack (https://github.com/python/typing/issues/196).
988n/a self.__next_in_mro__ = _next_in_mro(self)
989n/a # Preserve base classes on subclassing (__bases__ are type erased now).
990n/a if orig_bases is None:
991n/a self.__orig_bases__ = initial_bases
992n/a
993n/a # This allows unparameterized generic collections to be used
994n/a # with issubclass() and isinstance() in the same way as their
995n/a # collections.abc counterparts (e.g., isinstance([], Iterable)).
996n/a if (
997n/a # allow overriding
998n/a '__subclasshook__' not in namespace and extra or
999n/a hasattr(self.__subclasshook__, '__name__') and
1000n/a self.__subclasshook__.__name__ == '__extrahook__'
1001n/a ):
1002n/a self.__subclasshook__ = _make_subclasshook(self)
1003n/a if isinstance(extra, abc.ABCMeta):
1004n/a self._abc_registry = extra._abc_registry
1005n/a
1006n/a if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
1007n/a self.__qualname__ = origin.__qualname__
1008n/a self.__tree_hash__ = hash(self._subs_tree()) if origin else hash((self.__name__,))
1009n/a return self
1010n/a
1011n/a def _get_type_vars(self, tvars):
1012n/a if self.__origin__ and self.__parameters__:
1013n/a _get_type_vars(self.__parameters__, tvars)
1014n/a
1015n/a def _eval_type(self, globalns, localns):
1016n/a ev_origin = (self.__origin__._eval_type(globalns, localns)
1017n/a if self.__origin__ else None)
1018n/a ev_args = tuple(_eval_type(a, globalns, localns) for a
1019n/a in self.__args__) if self.__args__ else None
1020n/a if ev_origin == self.__origin__ and ev_args == self.__args__:
1021n/a return self
1022n/a return self.__class__(self.__name__,
1023n/a self.__bases__,
1024n/a _no_slots_copy(self.__dict__),
1025n/a tvars=_type_vars(ev_args) if ev_args else None,
1026n/a args=ev_args,
1027n/a origin=ev_origin,
1028n/a extra=self.__extra__,
1029n/a orig_bases=self.__orig_bases__)
1030n/a
1031n/a def __repr__(self):
1032n/a if self.__origin__ is None:
1033n/a return super().__repr__()
1034n/a return self._tree_repr(self._subs_tree())
1035n/a
1036n/a def _tree_repr(self, tree):
1037n/a arg_list = []
1038n/a for arg in tree[1:]:
1039n/a if arg == ():
1040n/a arg_list.append('()')
1041n/a elif not isinstance(arg, tuple):
1042n/a arg_list.append(_type_repr(arg))
1043n/a else:
1044n/a arg_list.append(arg[0]._tree_repr(arg))
1045n/a return super().__repr__() + '[%s]' % ', '.join(arg_list)
1046n/a
1047n/a def _subs_tree(self, tvars=None, args=None):
1048n/a if self.__origin__ is None:
1049n/a return self
1050n/a tree_args = _subs_tree(self, tvars, args)
1051n/a return (_gorg(self),) + tuple(tree_args)
1052n/a
1053n/a def __eq__(self, other):
1054n/a if not isinstance(other, GenericMeta):
1055n/a return NotImplemented
1056n/a if self.__origin__ is None or other.__origin__ is None:
1057n/a return self is other
1058n/a return self.__tree_hash__ == other.__tree_hash__
1059n/a
1060n/a def __hash__(self):
1061n/a return self.__tree_hash__
1062n/a
1063n/a @_tp_cache
1064n/a def __getitem__(self, params):
1065n/a if not isinstance(params, tuple):
1066n/a params = (params,)
1067n/a if not params and not _gorg(self) is Tuple:
1068n/a raise TypeError(
1069n/a "Parameter list to %s[...] cannot be empty" % _qualname(self))
1070n/a msg = "Parameters to generic types must be types."
1071n/a params = tuple(_type_check(p, msg) for p in params)
1072n/a if self is Generic:
1073n/a # Generic can only be subscripted with unique type variables.
1074n/a if not all(isinstance(p, TypeVar) for p in params):
1075n/a raise TypeError(
1076n/a "Parameters to Generic[...] must all be type variables")
1077n/a if len(set(params)) != len(params):
1078n/a raise TypeError(
1079n/a "Parameters to Generic[...] must all be unique")
1080n/a tvars = params
1081n/a args = params
1082n/a elif self in (Tuple, Callable):
1083n/a tvars = _type_vars(params)
1084n/a args = params
1085n/a elif self is _Protocol:
1086n/a # _Protocol is internal, don't check anything.
1087n/a tvars = params
1088n/a args = params
1089n/a elif self.__origin__ in (Generic, _Protocol):
1090n/a # Can't subscript Generic[...] or _Protocol[...].
1091n/a raise TypeError("Cannot subscript already-subscripted %s" %
1092n/a repr(self))
1093n/a else:
1094n/a # Subscripting a regular Generic subclass.
1095n/a _check_generic(self, params)
1096n/a tvars = _type_vars(params)
1097n/a args = params
1098n/a return self.__class__(self.__name__,
1099n/a self.__bases__,
1100n/a _no_slots_copy(self.__dict__),
1101n/a tvars=tvars,
1102n/a args=args,
1103n/a origin=self,
1104n/a extra=self.__extra__,
1105n/a orig_bases=self.__orig_bases__)
1106n/a
1107n/a def __instancecheck__(self, instance):
1108n/a # Since we extend ABC.__subclasscheck__ and
1109n/a # ABC.__instancecheck__ inlines the cache checking done by the
1110n/a # latter, we must extend __instancecheck__ too. For simplicity
1111n/a # we just skip the cache check -- instance checks for generic
1112n/a # classes are supposed to be rare anyways.
1113n/a return issubclass(instance.__class__, self)
1114n/a
1115n/a def __copy__(self):
1116n/a return self.__class__(self.__name__, self.__bases__,
1117n/a _no_slots_copy(self.__dict__),
1118n/a self.__parameters__, self.__args__, self.__origin__,
1119n/a self.__extra__, self.__orig_bases__)
1120n/a
1121n/a
1122n/a# Prevent checks for Generic to crash when defining Generic.
1123n/aGeneric = None
1124n/a
1125n/a
1126n/adef _generic_new(base_cls, cls, *args, **kwds):
1127n/a # Assure type is erased on instantiation,
1128n/a # but attempt to store it in __orig_class__
1129n/a if cls.__origin__ is None:
1130n/a return base_cls.__new__(cls)
1131n/a else:
1132n/a origin = _gorg(cls)
1133n/a obj = base_cls.__new__(origin)
1134n/a try:
1135n/a obj.__orig_class__ = cls
1136n/a except AttributeError:
1137n/a pass
1138n/a obj.__init__(*args, **kwds)
1139n/a return obj
1140n/a
1141n/a
1142n/aclass Generic(metaclass=GenericMeta):
1143n/a """Abstract base class for generic types.
1144n/a
1145n/a A generic type is typically declared by inheriting from
1146n/a this class parameterized with one or more type variables.
1147n/a For example, a generic mapping type might be defined as::
1148n/a
1149n/a class Mapping(Generic[KT, VT]):
1150n/a def __getitem__(self, key: KT) -> VT:
1151n/a ...
1152n/a # Etc.
1153n/a
1154n/a This class can then be used as follows::
1155n/a
1156n/a def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
1157n/a try:
1158n/a return mapping[key]
1159n/a except KeyError:
1160n/a return default
1161n/a """
1162n/a
1163n/a __slots__ = ()
1164n/a
1165n/a def __new__(cls, *args, **kwds):
1166n/a if _geqv(cls, Generic):
1167n/a raise TypeError("Type Generic cannot be instantiated; "
1168n/a "it can be used only as a base class")
1169n/a return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1170n/a
1171n/a
1172n/aclass _TypingEmpty:
1173n/a """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1174n/a to allow empty list/tuple in specific places, without allowing them
1175n/a to sneak in where prohibited.
1176n/a """
1177n/a
1178n/a
1179n/aclass _TypingEllipsis:
1180n/a """Internal placeholder for ... (ellipsis)."""
1181n/a
1182n/a
1183n/aclass TupleMeta(GenericMeta):
1184n/a """Metaclass for Tuple (internal)."""
1185n/a
1186n/a @_tp_cache
1187n/a def __getitem__(self, parameters):
1188n/a if self.__origin__ is not None or not _geqv(self, Tuple):
1189n/a # Normal generic rules apply if this is not the first subscription
1190n/a # or a subscription of a subclass.
1191n/a return super().__getitem__(parameters)
1192n/a if parameters == ():
1193n/a return super().__getitem__((_TypingEmpty,))
1194n/a if not isinstance(parameters, tuple):
1195n/a parameters = (parameters,)
1196n/a if len(parameters) == 2 and parameters[1] is ...:
1197n/a msg = "Tuple[t, ...]: t must be a type."
1198n/a p = _type_check(parameters[0], msg)
1199n/a return super().__getitem__((p, _TypingEllipsis))
1200n/a msg = "Tuple[t0, t1, ...]: each t must be a type."
1201n/a parameters = tuple(_type_check(p, msg) for p in parameters)
1202n/a return super().__getitem__(parameters)
1203n/a
1204n/a def __instancecheck__(self, obj):
1205n/a if self.__args__ is None:
1206n/a return isinstance(obj, tuple)
1207n/a raise TypeError("Parameterized Tuple cannot be used "
1208n/a "with isinstance().")
1209n/a
1210n/a def __subclasscheck__(self, cls):
1211n/a if self.__args__ is None:
1212n/a return issubclass(cls, tuple)
1213n/a raise TypeError("Parameterized Tuple cannot be used "
1214n/a "with issubclass().")
1215n/a
1216n/a
1217n/aclass Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1218n/a """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1219n/a
1220n/a Example: Tuple[T1, T2] is a tuple of two elements corresponding
1221n/a to type variables T1 and T2. Tuple[int, float, str] is a tuple
1222n/a of an int, a float and a string.
1223n/a
1224n/a To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1225n/a """
1226n/a
1227n/a __slots__ = ()
1228n/a
1229n/a def __new__(cls, *args, **kwds):
1230n/a if _geqv(cls, Tuple):
1231n/a raise TypeError("Type Tuple cannot be instantiated; "
1232n/a "use tuple() instead")
1233n/a return _generic_new(tuple, cls, *args, **kwds)
1234n/a
1235n/a
1236n/aclass CallableMeta(GenericMeta):
1237n/a """Metaclass for Callable (internal)."""
1238n/a
1239n/a def __repr__(self):
1240n/a if self.__origin__ is None:
1241n/a return super().__repr__()
1242n/a return self._tree_repr(self._subs_tree())
1243n/a
1244n/a def _tree_repr(self, tree):
1245n/a if _gorg(self) is not Callable:
1246n/a return super()._tree_repr(tree)
1247n/a # For actual Callable (not its subclass) we override
1248n/a # super()._tree_repr() for nice formatting.
1249n/a arg_list = []
1250n/a for arg in tree[1:]:
1251n/a if not isinstance(arg, tuple):
1252n/a arg_list.append(_type_repr(arg))
1253n/a else:
1254n/a arg_list.append(arg[0]._tree_repr(arg))
1255n/a if arg_list[0] == '...':
1256n/a return repr(tree[0]) + '[..., %s]' % arg_list[1]
1257n/a return (repr(tree[0]) +
1258n/a '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1259n/a
1260n/a def __getitem__(self, parameters):
1261n/a """A thin wrapper around __getitem_inner__ to provide the latter
1262n/a with hashable arguments to improve speed.
1263n/a """
1264n/a
1265n/a if self.__origin__ is not None or not _geqv(self, Callable):
1266n/a return super().__getitem__(parameters)
1267n/a if not isinstance(parameters, tuple) or len(parameters) != 2:
1268n/a raise TypeError("Callable must be used as "
1269n/a "Callable[[arg, ...], result].")
1270n/a args, result = parameters
1271n/a if args is Ellipsis:
1272n/a parameters = (Ellipsis, result)
1273n/a else:
1274n/a if not isinstance(args, list):
1275n/a raise TypeError("Callable[args, result]: args must be a list."
1276n/a " Got %.100r." % (args,))
1277n/a parameters = (tuple(args), result)
1278n/a return self.__getitem_inner__(parameters)
1279n/a
1280n/a @_tp_cache
1281n/a def __getitem_inner__(self, parameters):
1282n/a args, result = parameters
1283n/a msg = "Callable[args, result]: result must be a type."
1284n/a result = _type_check(result, msg)
1285n/a if args is Ellipsis:
1286n/a return super().__getitem__((_TypingEllipsis, result))
1287n/a msg = "Callable[[arg, ...], result]: each arg must be a type."
1288n/a args = tuple(_type_check(arg, msg) for arg in args)
1289n/a parameters = args + (result,)
1290n/a return super().__getitem__(parameters)
1291n/a
1292n/a
1293n/aclass Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
1294n/a """Callable type; Callable[[int], str] is a function of (int) -> str.
1295n/a
1296n/a The subscription syntax must always be used with exactly two
1297n/a values: the argument list and the return type. The argument list
1298n/a must be a list of types or ellipsis; the return type must be a single type.
1299n/a
1300n/a There is no syntax to indicate optional or keyword arguments,
1301n/a such function types are rarely used as callback types.
1302n/a """
1303n/a
1304n/a __slots__ = ()
1305n/a
1306n/a def __new__(cls, *args, **kwds):
1307n/a if _geqv(cls, Callable):
1308n/a raise TypeError("Type Callable cannot be instantiated; "
1309n/a "use a non-abstract subclass instead")
1310n/a return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1311n/a
1312n/a
1313n/aclass _ClassVar(_FinalTypingBase, _root=True):
1314n/a """Special type construct to mark class variables.
1315n/a
1316n/a An annotation wrapped in ClassVar indicates that a given
1317n/a attribute is intended to be used as a class variable and
1318n/a should not be set on instances of that class. Usage::
1319n/a
1320n/a class Starship:
1321n/a stats: ClassVar[Dict[str, int]] = {} # class variable
1322n/a damage: int = 10 # instance variable
1323n/a
1324n/a ClassVar accepts only types and cannot be further subscribed.
1325n/a
1326n/a Note that ClassVar is not a class itself, and should not
1327n/a be used with isinstance() or issubclass().
1328n/a """
1329n/a
1330n/a __slots__ = ('__type__',)
1331n/a
1332n/a def __init__(self, tp=None, **kwds):
1333n/a self.__type__ = tp
1334n/a
1335n/a def __getitem__(self, item):
1336n/a cls = type(self)
1337n/a if self.__type__ is None:
1338n/a return cls(_type_check(item,
1339n/a '{} accepts only single type.'.format(cls.__name__[1:])),
1340n/a _root=True)
1341n/a raise TypeError('{} cannot be further subscripted'
1342n/a .format(cls.__name__[1:]))
1343n/a
1344n/a def _eval_type(self, globalns, localns):
1345n/a new_tp = _eval_type(self.__type__, globalns, localns)
1346n/a if new_tp == self.__type__:
1347n/a return self
1348n/a return type(self)(new_tp, _root=True)
1349n/a
1350n/a def __repr__(self):
1351n/a r = super().__repr__()
1352n/a if self.__type__ is not None:
1353n/a r += '[{}]'.format(_type_repr(self.__type__))
1354n/a return r
1355n/a
1356n/a def __hash__(self):
1357n/a return hash((type(self).__name__, self.__type__))
1358n/a
1359n/a def __eq__(self, other):
1360n/a if not isinstance(other, _ClassVar):
1361n/a return NotImplemented
1362n/a if self.__type__ is not None:
1363n/a return self.__type__ == other.__type__
1364n/a return self is other
1365n/a
1366n/a
1367n/aClassVar = _ClassVar(_root=True)
1368n/a
1369n/a
1370n/adef cast(typ, val):
1371n/a """Cast a value to a type.
1372n/a
1373n/a This returns the value unchanged. To the type checker this
1374n/a signals that the return value has the designated type, but at
1375n/a runtime we intentionally don't check anything (we want this
1376n/a to be as fast as possible).
1377n/a """
1378n/a return val
1379n/a
1380n/a
1381n/adef _get_defaults(func):
1382n/a """Internal helper to extract the default arguments, by name."""
1383n/a try:
1384n/a code = func.__code__
1385n/a except AttributeError:
1386n/a # Some built-in functions don't have __code__, __defaults__, etc.
1387n/a return {}
1388n/a pos_count = code.co_argcount
1389n/a arg_names = code.co_varnames
1390n/a arg_names = arg_names[:pos_count]
1391n/a defaults = func.__defaults__ or ()
1392n/a kwdefaults = func.__kwdefaults__
1393n/a res = dict(kwdefaults) if kwdefaults else {}
1394n/a pos_offset = pos_count - len(defaults)
1395n/a for name, value in zip(arg_names[pos_offset:], defaults):
1396n/a assert name not in res
1397n/a res[name] = value
1398n/a return res
1399n/a
1400n/a
1401n/adef get_type_hints(obj, globalns=None, localns=None):
1402n/a """Return type hints for an object.
1403n/a
1404n/a This is often the same as obj.__annotations__, but it handles
1405n/a forward references encoded as string literals, and if necessary
1406n/a adds Optional[t] if a default value equal to None is set.
1407n/a
1408n/a The argument may be a module, class, method, or function. The annotations
1409n/a are returned as a dictionary. For classes, annotations include also
1410n/a inherited members.
1411n/a
1412n/a TypeError is raised if the argument is not of a type that can contain
1413n/a annotations, and an empty dictionary is returned if no annotations are
1414n/a present.
1415n/a
1416n/a BEWARE -- the behavior of globalns and localns is counterintuitive
1417n/a (unless you are familiar with how eval() and exec() work). The
1418n/a search order is locals first, then globals.
1419n/a
1420n/a - If no dict arguments are passed, an attempt is made to use the
1421n/a globals from obj, and these are also used as the locals. If the
1422n/a object does not appear to have globals, an exception is raised.
1423n/a
1424n/a - If one dict argument is passed, it is used for both globals and
1425n/a locals.
1426n/a
1427n/a - If two dict arguments are passed, they specify globals and
1428n/a locals, respectively.
1429n/a """
1430n/a
1431n/a if getattr(obj, '__no_type_check__', None):
1432n/a return {}
1433n/a if globalns is None:
1434n/a globalns = getattr(obj, '__globals__', {})
1435n/a if localns is None:
1436n/a localns = globalns
1437n/a elif localns is None:
1438n/a localns = globalns
1439n/a # Classes require a special treatment.
1440n/a if isinstance(obj, type):
1441n/a hints = {}
1442n/a for base in reversed(obj.__mro__):
1443n/a ann = base.__dict__.get('__annotations__', {})
1444n/a for name, value in ann.items():
1445n/a if value is None:
1446n/a value = type(None)
1447n/a if isinstance(value, str):
1448n/a value = _ForwardRef(value)
1449n/a value = _eval_type(value, globalns, localns)
1450n/a hints[name] = value
1451n/a return hints
1452n/a hints = getattr(obj, '__annotations__', None)
1453n/a if hints is None:
1454n/a # Return empty annotations for something that _could_ have them.
1455n/a if (
1456n/a isinstance(obj, types.FunctionType) or
1457n/a isinstance(obj, types.BuiltinFunctionType) or
1458n/a isinstance(obj, types.MethodType) or
1459n/a isinstance(obj, types.ModuleType)
1460n/a ):
1461n/a return {}
1462n/a else:
1463n/a raise TypeError('{!r} is not a module, class, method, '
1464n/a 'or function.'.format(obj))
1465n/a defaults = _get_defaults(obj)
1466n/a hints = dict(hints)
1467n/a for name, value in hints.items():
1468n/a if value is None:
1469n/a value = type(None)
1470n/a if isinstance(value, str):
1471n/a value = _ForwardRef(value)
1472n/a value = _eval_type(value, globalns, localns)
1473n/a if name in defaults and defaults[name] is None:
1474n/a value = Optional[value]
1475n/a hints[name] = value
1476n/a return hints
1477n/a
1478n/a
1479n/adef no_type_check(arg):
1480n/a """Decorator to indicate that annotations are not type hints.
1481n/a
1482n/a The argument must be a class or function; if it is a class, it
1483n/a applies recursively to all methods and classes defined in that class
1484n/a (but not to methods defined in its superclasses or subclasses).
1485n/a
1486n/a This mutates the function(s) or class(es) in place.
1487n/a """
1488n/a if isinstance(arg, type):
1489n/a arg_attrs = arg.__dict__.copy()
1490n/a for attr, val in arg.__dict__.items():
1491n/a if val in arg.__bases__:
1492n/a arg_attrs.pop(attr)
1493n/a for obj in arg_attrs.values():
1494n/a if isinstance(obj, types.FunctionType):
1495n/a obj.__no_type_check__ = True
1496n/a if isinstance(obj, type):
1497n/a no_type_check(obj)
1498n/a try:
1499n/a arg.__no_type_check__ = True
1500n/a except TypeError: # built-in classes
1501n/a pass
1502n/a return arg
1503n/a
1504n/a
1505n/adef no_type_check_decorator(decorator):
1506n/a """Decorator to give another decorator the @no_type_check effect.
1507n/a
1508n/a This wraps the decorator with something that wraps the decorated
1509n/a function in @no_type_check.
1510n/a """
1511n/a
1512n/a @functools.wraps(decorator)
1513n/a def wrapped_decorator(*args, **kwds):
1514n/a func = decorator(*args, **kwds)
1515n/a func = no_type_check(func)
1516n/a return func
1517n/a
1518n/a return wrapped_decorator
1519n/a
1520n/a
1521n/adef _overload_dummy(*args, **kwds):
1522n/a """Helper for @overload to raise when called."""
1523n/a raise NotImplementedError(
1524n/a "You should not call an overloaded function. "
1525n/a "A series of @overload-decorated functions "
1526n/a "outside a stub module should always be followed "
1527n/a "by an implementation that is not @overload-ed.")
1528n/a
1529n/a
1530n/adef overload(func):
1531n/a """Decorator for overloaded functions/methods.
1532n/a
1533n/a In a stub file, place two or more stub definitions for the same
1534n/a function in a row, each decorated with @overload. For example:
1535n/a
1536n/a @overload
1537n/a def utf8(value: None) -> None: ...
1538n/a @overload
1539n/a def utf8(value: bytes) -> bytes: ...
1540n/a @overload
1541n/a def utf8(value: str) -> bytes: ...
1542n/a
1543n/a In a non-stub file (i.e. a regular .py file), do the same but
1544n/a follow it with an implementation. The implementation should *not*
1545n/a be decorated with @overload. For example:
1546n/a
1547n/a @overload
1548n/a def utf8(value: None) -> None: ...
1549n/a @overload
1550n/a def utf8(value: bytes) -> bytes: ...
1551n/a @overload
1552n/a def utf8(value: str) -> bytes: ...
1553n/a def utf8(value):
1554n/a # implementation goes here
1555n/a """
1556n/a return _overload_dummy
1557n/a
1558n/a
1559n/aclass _ProtocolMeta(GenericMeta):
1560n/a """Internal metaclass for _Protocol.
1561n/a
1562n/a This exists so _Protocol classes can be generic without deriving
1563n/a from Generic.
1564n/a """
1565n/a
1566n/a def __instancecheck__(self, obj):
1567n/a if _Protocol not in self.__bases__:
1568n/a return super().__instancecheck__(obj)
1569n/a raise TypeError("Protocols cannot be used with isinstance().")
1570n/a
1571n/a def __subclasscheck__(self, cls):
1572n/a if not self._is_protocol:
1573n/a # No structural checks since this isn't a protocol.
1574n/a return NotImplemented
1575n/a
1576n/a if self is _Protocol:
1577n/a # Every class is a subclass of the empty protocol.
1578n/a return True
1579n/a
1580n/a # Find all attributes defined in the protocol.
1581n/a attrs = self._get_protocol_attrs()
1582n/a
1583n/a for attr in attrs:
1584n/a if not any(attr in d.__dict__ for d in cls.__mro__):
1585n/a return False
1586n/a return True
1587n/a
1588n/a def _get_protocol_attrs(self):
1589n/a # Get all Protocol base classes.
1590n/a protocol_bases = []
1591n/a for c in self.__mro__:
1592n/a if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1593n/a protocol_bases.append(c)
1594n/a
1595n/a # Get attributes included in protocol.
1596n/a attrs = set()
1597n/a for base in protocol_bases:
1598n/a for attr in base.__dict__.keys():
1599n/a # Include attributes not defined in any non-protocol bases.
1600n/a for c in self.__mro__:
1601n/a if (c is not base and attr in c.__dict__ and
1602n/a not getattr(c, '_is_protocol', False)):
1603n/a break
1604n/a else:
1605n/a if (not attr.startswith('_abc_') and
1606n/a attr != '__abstractmethods__' and
1607n/a attr != '__annotations__' and
1608n/a attr != '__weakref__' and
1609n/a attr != '_is_protocol' and
1610n/a attr != '__dict__' and
1611n/a attr != '__args__' and
1612n/a attr != '__slots__' and
1613n/a attr != '_get_protocol_attrs' and
1614n/a attr != '__next_in_mro__' and
1615n/a attr != '__parameters__' and
1616n/a attr != '__origin__' and
1617n/a attr != '__orig_bases__' and
1618n/a attr != '__extra__' and
1619n/a attr != '__tree_hash__' and
1620n/a attr != '__module__'):
1621n/a attrs.add(attr)
1622n/a
1623n/a return attrs
1624n/a
1625n/a
1626n/aclass _Protocol(metaclass=_ProtocolMeta):
1627n/a """Internal base class for protocol classes.
1628n/a
1629n/a This implements a simple-minded structural issubclass check
1630n/a (similar but more general than the one-offs in collections.abc
1631n/a such as Hashable).
1632n/a """
1633n/a
1634n/a __slots__ = ()
1635n/a
1636n/a _is_protocol = True
1637n/a
1638n/a
1639n/a# Various ABCs mimicking those in collections.abc.
1640n/a# A few are simply re-exported for completeness.
1641n/a
1642n/aHashable = collections_abc.Hashable # Not generic.
1643n/a
1644n/a
1645n/aif hasattr(collections_abc, 'Awaitable'):
1646n/a class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1647n/a __slots__ = ()
1648n/a
1649n/a __all__.append('Awaitable')
1650n/a
1651n/a
1652n/aif hasattr(collections_abc, 'Coroutine'):
1653n/a class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1654n/a extra=collections_abc.Coroutine):
1655n/a __slots__ = ()
1656n/a
1657n/a __all__.append('Coroutine')
1658n/a
1659n/a
1660n/aif hasattr(collections_abc, 'AsyncIterable'):
1661n/a
1662n/a class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1663n/a __slots__ = ()
1664n/a
1665n/a class AsyncIterator(AsyncIterable[T_co],
1666n/a extra=collections_abc.AsyncIterator):
1667n/a __slots__ = ()
1668n/a
1669n/a __all__.append('AsyncIterable')
1670n/a __all__.append('AsyncIterator')
1671n/a
1672n/a
1673n/aclass Iterable(Generic[T_co], extra=collections_abc.Iterable):
1674n/a __slots__ = ()
1675n/a
1676n/a
1677n/aclass Iterator(Iterable[T_co], extra=collections_abc.Iterator):
1678n/a __slots__ = ()
1679n/a
1680n/a
1681n/aclass SupportsInt(_Protocol):
1682n/a __slots__ = ()
1683n/a
1684n/a @abstractmethod
1685n/a def __int__(self) -> int:
1686n/a pass
1687n/a
1688n/a
1689n/aclass SupportsFloat(_Protocol):
1690n/a __slots__ = ()
1691n/a
1692n/a @abstractmethod
1693n/a def __float__(self) -> float:
1694n/a pass
1695n/a
1696n/a
1697n/aclass SupportsComplex(_Protocol):
1698n/a __slots__ = ()
1699n/a
1700n/a @abstractmethod
1701n/a def __complex__(self) -> complex:
1702n/a pass
1703n/a
1704n/a
1705n/aclass SupportsBytes(_Protocol):
1706n/a __slots__ = ()
1707n/a
1708n/a @abstractmethod
1709n/a def __bytes__(self) -> bytes:
1710n/a pass
1711n/a
1712n/a
1713n/aclass SupportsAbs(_Protocol[T_co]):
1714n/a __slots__ = ()
1715n/a
1716n/a @abstractmethod
1717n/a def __abs__(self) -> T_co:
1718n/a pass
1719n/a
1720n/a
1721n/aclass SupportsRound(_Protocol[T_co]):
1722n/a __slots__ = ()
1723n/a
1724n/a @abstractmethod
1725n/a def __round__(self, ndigits: int = 0) -> T_co:
1726n/a pass
1727n/a
1728n/a
1729n/aif hasattr(collections_abc, 'Reversible'):
1730n/a class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1731n/a __slots__ = ()
1732n/aelse:
1733n/a class Reversible(_Protocol[T_co]):
1734n/a __slots__ = ()
1735n/a
1736n/a @abstractmethod
1737n/a def __reversed__(self) -> 'Iterator[T_co]':
1738n/a pass
1739n/a
1740n/a
1741n/aSized = collections_abc.Sized # Not generic.
1742n/a
1743n/a
1744n/aclass Container(Generic[T_co], extra=collections_abc.Container):
1745n/a __slots__ = ()
1746n/a
1747n/a
1748n/aif hasattr(collections_abc, 'Collection'):
1749n/a class Collection(Sized, Iterable[T_co], Container[T_co],
1750n/a extra=collections_abc.Collection):
1751n/a __slots__ = ()
1752n/a
1753n/a __all__.append('Collection')
1754n/a
1755n/a
1756n/a# Callable was defined earlier.
1757n/a
1758n/aif hasattr(collections_abc, 'Collection'):
1759n/a class AbstractSet(Collection[T_co],
1760n/a extra=collections_abc.Set):
1761n/a __slots__ = ()
1762n/aelse:
1763n/a class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1764n/a extra=collections_abc.Set):
1765n/a __slots__ = ()
1766n/a
1767n/a
1768n/aclass MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
1769n/a __slots__ = ()
1770n/a
1771n/a
1772n/a# NOTE: It is only covariant in the value type.
1773n/aif hasattr(collections_abc, 'Collection'):
1774n/a class Mapping(Collection[KT], Generic[KT, VT_co],
1775n/a extra=collections_abc.Mapping):
1776n/a __slots__ = ()
1777n/aelse:
1778n/a class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1779n/a extra=collections_abc.Mapping):
1780n/a __slots__ = ()
1781n/a
1782n/a
1783n/aclass MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
1784n/a __slots__ = ()
1785n/a
1786n/a
1787n/aif hasattr(collections_abc, 'Reversible'):
1788n/a if hasattr(collections_abc, 'Collection'):
1789n/a class Sequence(Reversible[T_co], Collection[T_co],
1790n/a extra=collections_abc.Sequence):
1791n/a __slots__ = ()
1792n/a else:
1793n/a class Sequence(Sized, Reversible[T_co], Container[T_co],
1794n/a extra=collections_abc.Sequence):
1795n/a __slots__ = ()
1796n/aelse:
1797n/a class Sequence(Sized, Iterable[T_co], Container[T_co],
1798n/a extra=collections_abc.Sequence):
1799n/a __slots__ = ()
1800n/a
1801n/a
1802n/aclass MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
1803n/a __slots__ = ()
1804n/a
1805n/a
1806n/aclass ByteString(Sequence[int], extra=collections_abc.ByteString):
1807n/a __slots__ = ()
1808n/a
1809n/a
1810n/aclass List(list, MutableSequence[T], extra=list):
1811n/a
1812n/a __slots__ = ()
1813n/a
1814n/a def __new__(cls, *args, **kwds):
1815n/a if _geqv(cls, List):
1816n/a raise TypeError("Type List cannot be instantiated; "
1817n/a "use list() instead")
1818n/a return _generic_new(list, cls, *args, **kwds)
1819n/a
1820n/a
1821n/aclass Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1822n/a
1823n/a __slots__ = ()
1824n/a
1825n/a def __new__(cls, *args, **kwds):
1826n/a if _geqv(cls, Deque):
1827n/a raise TypeError("Type Deque cannot be instantiated; "
1828n/a "use deque() instead")
1829n/a return _generic_new(collections.deque, cls, *args, **kwds)
1830n/a
1831n/a
1832n/aclass Set(set, MutableSet[T], extra=set):
1833n/a
1834n/a __slots__ = ()
1835n/a
1836n/a def __new__(cls, *args, **kwds):
1837n/a if _geqv(cls, Set):
1838n/a raise TypeError("Type Set cannot be instantiated; "
1839n/a "use set() instead")
1840n/a return _generic_new(set, cls, *args, **kwds)
1841n/a
1842n/a
1843n/aclass FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
1844n/a __slots__ = ()
1845n/a
1846n/a def __new__(cls, *args, **kwds):
1847n/a if _geqv(cls, FrozenSet):
1848n/a raise TypeError("Type FrozenSet cannot be instantiated; "
1849n/a "use frozenset() instead")
1850n/a return _generic_new(frozenset, cls, *args, **kwds)
1851n/a
1852n/a
1853n/aclass MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
1854n/a __slots__ = ()
1855n/a
1856n/a
1857n/aclass KeysView(MappingView[KT], AbstractSet[KT],
1858n/a extra=collections_abc.KeysView):
1859n/a __slots__ = ()
1860n/a
1861n/a
1862n/aclass ItemsView(MappingView[Tuple[KT, VT_co]],
1863n/a AbstractSet[Tuple[KT, VT_co]],
1864n/a Generic[KT, VT_co],
1865n/a extra=collections_abc.ItemsView):
1866n/a __slots__ = ()
1867n/a
1868n/a
1869n/aclass ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
1870n/a __slots__ = ()
1871n/a
1872n/a
1873n/aif hasattr(contextlib, 'AbstractContextManager'):
1874n/a class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1875n/a __slots__ = ()
1876n/a __all__.append('ContextManager')
1877n/a
1878n/a
1879n/aclass Dict(dict, MutableMapping[KT, VT], extra=dict):
1880n/a
1881n/a __slots__ = ()
1882n/a
1883n/a def __new__(cls, *args, **kwds):
1884n/a if _geqv(cls, Dict):
1885n/a raise TypeError("Type Dict cannot be instantiated; "
1886n/a "use dict() instead")
1887n/a return _generic_new(dict, cls, *args, **kwds)
1888n/a
1889n/a
1890n/aclass DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1891n/a extra=collections.defaultdict):
1892n/a
1893n/a __slots__ = ()
1894n/a
1895n/a def __new__(cls, *args, **kwds):
1896n/a if _geqv(cls, DefaultDict):
1897n/a raise TypeError("Type DefaultDict cannot be instantiated; "
1898n/a "use collections.defaultdict() instead")
1899n/a return _generic_new(collections.defaultdict, cls, *args, **kwds)
1900n/a
1901n/a
1902n/a# Determine what base class to use for Generator.
1903n/aif hasattr(collections_abc, 'Generator'):
1904n/a # Sufficiently recent versions of 3.5 have a Generator ABC.
1905n/a _G_base = collections_abc.Generator
1906n/aelse:
1907n/a # Fall back on the exact type.
1908n/a _G_base = types.GeneratorType
1909n/a
1910n/a
1911n/aclass Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1912n/a extra=_G_base):
1913n/a __slots__ = ()
1914n/a
1915n/a def __new__(cls, *args, **kwds):
1916n/a if _geqv(cls, Generator):
1917n/a raise TypeError("Type Generator cannot be instantiated; "
1918n/a "create a subclass instead")
1919n/a return _generic_new(_G_base, cls, *args, **kwds)
1920n/a
1921n/a
1922n/aif hasattr(collections_abc, 'AsyncGenerator'):
1923n/a class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
1924n/a extra=collections_abc.AsyncGenerator):
1925n/a __slots__ = ()
1926n/a
1927n/a __all__.append('AsyncGenerator')
1928n/a
1929n/a
1930n/a# Internal type variable used for Type[].
1931n/aCT_co = TypeVar('CT_co', covariant=True, bound=type)
1932n/a
1933n/a
1934n/a# This is not a real generic class. Don't use outside annotations.
1935n/aclass Type(Generic[CT_co], extra=type):
1936n/a """A special construct usable to annotate class objects.
1937n/a
1938n/a For example, suppose we have the following classes::
1939n/a
1940n/a class User: ... # Abstract base for User classes
1941n/a class BasicUser(User): ...
1942n/a class ProUser(User): ...
1943n/a class TeamUser(User): ...
1944n/a
1945n/a And a function that takes a class argument that's a subclass of
1946n/a User and returns an instance of the corresponding class::
1947n/a
1948n/a U = TypeVar('U', bound=User)
1949n/a def new_user(user_class: Type[U]) -> U:
1950n/a user = user_class()
1951n/a # (Here we could write the user object to a database)
1952n/a return user
1953n/a
1954n/a joe = new_user(BasicUser)
1955n/a
1956n/a At this point the type checker knows that joe has type BasicUser.
1957n/a """
1958n/a
1959n/a __slots__ = ()
1960n/a
1961n/a
1962n/adef _make_nmtuple(name, types):
1963n/a msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1964n/a types = [(n, _type_check(t, msg)) for n, t in types]
1965n/a nm_tpl = collections.namedtuple(name, [n for n, t in types])
1966n/a # Prior to PEP 526, only _field_types attribute was assigned.
1967n/a # Now, both __annotations__ and _field_types are used to maintain compatibility.
1968n/a nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
1969n/a try:
1970n/a nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
1971n/a except (AttributeError, ValueError):
1972n/a pass
1973n/a return nm_tpl
1974n/a
1975n/a
1976n/a_PY36 = sys.version_info[:2] >= (3, 6)
1977n/a
1978n/a
1979n/aclass NamedTupleMeta(type):
1980n/a
1981n/a def __new__(cls, typename, bases, ns):
1982n/a if ns.get('_root', False):
1983n/a return super().__new__(cls, typename, bases, ns)
1984n/a if not _PY36:
1985n/a raise TypeError("Class syntax for NamedTuple is only supported"
1986n/a " in Python 3.6+")
1987n/a types = ns.get('__annotations__', {})
1988n/a nm_tpl = _make_nmtuple(typename, types.items())
1989n/a defaults = []
1990n/a defaults_dict = {}
1991n/a for field_name in types:
1992n/a if field_name in ns:
1993n/a default_value = ns[field_name]
1994n/a defaults.append(default_value)
1995n/a defaults_dict[field_name] = default_value
1996n/a elif defaults:
1997n/a raise TypeError("Non-default namedtuple field {field_name} cannot "
1998n/a "follow default field(s) {default_names}"
1999n/a .format(field_name=field_name,
2000n/a default_names=', '.join(defaults_dict.keys())))
2001n/a nm_tpl.__new__.__defaults__ = tuple(defaults)
2002n/a nm_tpl._field_defaults = defaults_dict
2003n/a # update from user namespace without overriding special namedtuple attributes
2004n/a for key in ns:
2005n/a if not hasattr(nm_tpl, key):
2006n/a setattr(nm_tpl, key, ns[key])
2007n/a return nm_tpl
2008n/a
2009n/a
2010n/aclass NamedTuple(metaclass=NamedTupleMeta):
2011n/a """Typed version of namedtuple.
2012n/a
2013n/a Usage in Python versions >= 3.6::
2014n/a
2015n/a class Employee(NamedTuple):
2016n/a name: str
2017n/a id: int
2018n/a
2019n/a This is equivalent to::
2020n/a
2021n/a Employee = collections.namedtuple('Employee', ['name', 'id'])
2022n/a
2023n/a The resulting class has extra __annotations__ and _field_types
2024n/a attributes, giving an ordered dict mapping field names to types.
2025n/a __annotations__ should be preferred, while _field_types
2026n/a is kept to maintain pre PEP 526 compatibility. (The field names
2027n/a are in the _fields attribute, which is part of the namedtuple
2028n/a API.) Alternative equivalent keyword syntax is also accepted::
2029n/a
2030n/a Employee = NamedTuple('Employee', name=str, id=int)
2031n/a
2032n/a In Python versions <= 3.5 use::
2033n/a
2034n/a Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2035n/a """
2036n/a _root = True
2037n/a
2038n/a def __new__(self, typename, fields=None, **kwargs):
2039n/a if kwargs and not _PY36:
2040n/a raise TypeError("Keyword syntax for NamedTuple is only supported"
2041n/a " in Python 3.6+")
2042n/a if fields is None:
2043n/a fields = kwargs.items()
2044n/a elif kwargs:
2045n/a raise TypeError("Either list of fields or keywords"
2046n/a " can be provided to NamedTuple, not both")
2047n/a return _make_nmtuple(typename, fields)
2048n/a
2049n/a
2050n/adef NewType(name, tp):
2051n/a """NewType creates simple unique types with almost zero
2052n/a runtime overhead. NewType(name, tp) is considered a subtype of tp
2053n/a by static type checkers. At runtime, NewType(name, tp) returns
2054n/a a dummy function that simply returns its argument. Usage::
2055n/a
2056n/a UserId = NewType('UserId', int)
2057n/a
2058n/a def name_by_id(user_id: UserId) -> str:
2059n/a ...
2060n/a
2061n/a UserId('user') # Fails type check
2062n/a
2063n/a name_by_id(42) # Fails type check
2064n/a name_by_id(UserId(42)) # OK
2065n/a
2066n/a num = UserId(5) + 1 # type: int
2067n/a """
2068n/a
2069n/a def new_type(x):
2070n/a return x
2071n/a
2072n/a new_type.__name__ = name
2073n/a new_type.__supertype__ = tp
2074n/a return new_type
2075n/a
2076n/a
2077n/a# Python-version-specific alias (Python 2: unicode; Python 3: str)
2078n/aText = str
2079n/a
2080n/a
2081n/a# Constant that's True when type checking, but False here.
2082n/aTYPE_CHECKING = False
2083n/a
2084n/a
2085n/aclass IO(Generic[AnyStr]):
2086n/a """Generic base class for TextIO and BinaryIO.
2087n/a
2088n/a This is an abstract, generic version of the return of open().
2089n/a
2090n/a NOTE: This does not distinguish between the different possible
2091n/a classes (text vs. binary, read vs. write vs. read/write,
2092n/a append-only, unbuffered). The TextIO and BinaryIO subclasses
2093n/a below capture the distinctions between text vs. binary, which is
2094n/a pervasive in the interface; however we currently do not offer a
2095n/a way to track the other distinctions in the type system.
2096n/a """
2097n/a
2098n/a __slots__ = ()
2099n/a
2100n/a @abstractproperty
2101n/a def mode(self) -> str:
2102n/a pass
2103n/a
2104n/a @abstractproperty
2105n/a def name(self) -> str:
2106n/a pass
2107n/a
2108n/a @abstractmethod
2109n/a def close(self) -> None:
2110n/a pass
2111n/a
2112n/a @abstractmethod
2113n/a def closed(self) -> bool:
2114n/a pass
2115n/a
2116n/a @abstractmethod
2117n/a def fileno(self) -> int:
2118n/a pass
2119n/a
2120n/a @abstractmethod
2121n/a def flush(self) -> None:
2122n/a pass
2123n/a
2124n/a @abstractmethod
2125n/a def isatty(self) -> bool:
2126n/a pass
2127n/a
2128n/a @abstractmethod
2129n/a def read(self, n: int = -1) -> AnyStr:
2130n/a pass
2131n/a
2132n/a @abstractmethod
2133n/a def readable(self) -> bool:
2134n/a pass
2135n/a
2136n/a @abstractmethod
2137n/a def readline(self, limit: int = -1) -> AnyStr:
2138n/a pass
2139n/a
2140n/a @abstractmethod
2141n/a def readlines(self, hint: int = -1) -> List[AnyStr]:
2142n/a pass
2143n/a
2144n/a @abstractmethod
2145n/a def seek(self, offset: int, whence: int = 0) -> int:
2146n/a pass
2147n/a
2148n/a @abstractmethod
2149n/a def seekable(self) -> bool:
2150n/a pass
2151n/a
2152n/a @abstractmethod
2153n/a def tell(self) -> int:
2154n/a pass
2155n/a
2156n/a @abstractmethod
2157n/a def truncate(self, size: int = None) -> int:
2158n/a pass
2159n/a
2160n/a @abstractmethod
2161n/a def writable(self) -> bool:
2162n/a pass
2163n/a
2164n/a @abstractmethod
2165n/a def write(self, s: AnyStr) -> int:
2166n/a pass
2167n/a
2168n/a @abstractmethod
2169n/a def writelines(self, lines: List[AnyStr]) -> None:
2170n/a pass
2171n/a
2172n/a @abstractmethod
2173n/a def __enter__(self) -> 'IO[AnyStr]':
2174n/a pass
2175n/a
2176n/a @abstractmethod
2177n/a def __exit__(self, type, value, traceback) -> None:
2178n/a pass
2179n/a
2180n/a
2181n/aclass BinaryIO(IO[bytes]):
2182n/a """Typed version of the return of open() in binary mode."""
2183n/a
2184n/a __slots__ = ()
2185n/a
2186n/a @abstractmethod
2187n/a def write(self, s: Union[bytes, bytearray]) -> int:
2188n/a pass
2189n/a
2190n/a @abstractmethod
2191n/a def __enter__(self) -> 'BinaryIO':
2192n/a pass
2193n/a
2194n/a
2195n/aclass TextIO(IO[str]):
2196n/a """Typed version of the return of open() in text mode."""
2197n/a
2198n/a __slots__ = ()
2199n/a
2200n/a @abstractproperty
2201n/a def buffer(self) -> BinaryIO:
2202n/a pass
2203n/a
2204n/a @abstractproperty
2205n/a def encoding(self) -> str:
2206n/a pass
2207n/a
2208n/a @abstractproperty
2209n/a def errors(self) -> Optional[str]:
2210n/a pass
2211n/a
2212n/a @abstractproperty
2213n/a def line_buffering(self) -> bool:
2214n/a pass
2215n/a
2216n/a @abstractproperty
2217n/a def newlines(self) -> Any:
2218n/a pass
2219n/a
2220n/a @abstractmethod
2221n/a def __enter__(self) -> 'TextIO':
2222n/a pass
2223n/a
2224n/a
2225n/aclass io:
2226n/a """Wrapper namespace for IO generic classes."""
2227n/a
2228n/a __all__ = ['IO', 'TextIO', 'BinaryIO']
2229n/a IO = IO
2230n/a TextIO = TextIO
2231n/a BinaryIO = BinaryIO
2232n/a
2233n/a
2234n/aio.__name__ = __name__ + '.io'
2235n/asys.modules[io.__name__] = io
2236n/a
2237n/a
2238n/aPattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2239n/a lambda p: p.pattern)
2240n/aMatch = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2241n/a lambda m: m.re.pattern)
2242n/a
2243n/a
2244n/aclass re:
2245n/a """Wrapper namespace for re type aliases."""
2246n/a
2247n/a __all__ = ['Pattern', 'Match']
2248n/a Pattern = Pattern
2249n/a Match = Match
2250n/a
2251n/a
2252n/are.__name__ = __name__ + '.re'
2253n/asys.modules[re.__name__] = re