💾 Archived View for tris.fyi › pydoc › typing captured on 2022-01-08 at 13:43:39. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
The typing module: Support for gradual typing as defined by PEP 484. At large scale, the structure of the module is following:
Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).
mro(self, /) Return a type's method resolution order.
register(cls, subclass) Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator.
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. 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()]
Typed version of the return of open() in binary mode.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: Union[bytes, bytearray]) -> int
writelines(self, lines: List[~AnyStr]) -> None
closed = <property object at 0x7f0567898a90>
mode = <property object at 0x7f05678989f0>
name = <property object at 0x7f0567898a40>
Internal wrapper to hold a forward reference.
Abstract base class for generic types. 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]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default
Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
Generic base class for TextIO and BinaryIO. This is an abstract, generic version of the return of open(). NOTE: This does not distinguish between the different possible classes (text vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO and BinaryIO subclasses below capture the distinctions between text vs. binary, which is pervasive in the interface; however we currently do not offer a way to track the other distinctions in the type system.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: ~AnyStr) -> int
writelines(self, lines: List[~AnyStr]) -> None
closed = <property object at 0x7f0567898a90>
mode = <property object at 0x7f05678989f0>
name = <property object at 0x7f0567898a40>
<attribute '__doc__' of 'method_descriptor' objects>
<attribute '__doc__' of 'method-wrapper' objects>
mro(self, /) Return a type's method resolution order.
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.runtime_checkable act as simple-minded runtime protocols that check 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: ...
An ABC with one abstract method __abs__ that is covariant in its return type.
An ABC with one abstract method __bytes__.
An ABC with one abstract method __complex__.
An ABC with one abstract method __float__.
An ABC with one abstract method __index__.
An ABC with one abstract method __int__.
An ABC with one abstract method __round__ that is covariant in its return type.
str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
capitalize(self, /) Return a capitalized version of the string. More specifically, make the first character have upper case and the rest lower case.
casefold(self, /) Return a version of the string suitable for caseless comparisons.
center(self, width, fillchar=' ', /) Return a centered string of length width. Padding is done using the specified fill character (default is a space).
count(...) S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
encode(self, /, encoding='utf-8', errors='strict') Encode the string using the codec registered for encoding. encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
endswith(...) S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
expandtabs(self, /, tabsize=8) Return a copy where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed.
find(...) S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
format(...) S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
format_map(...) S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').
index(...) S.index(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.
isalnum(self, /) Return True if the string is an alpha-numeric string, False otherwise. A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
isalpha(self, /) Return True if the string is an alphabetic string, False otherwise. A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
isascii(self, /) Return True if all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
isdecimal(self, /) Return True if the string is a decimal string, False otherwise. A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
isdigit(self, /) Return True if the string is a digit string, False otherwise. A string is a digit string if all characters in the string are digits and there is at least one character in the string.
isidentifier(self, /) Return True if the string is a valid Python identifier, False otherwise. Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as "def" or "class".
islower(self, /) Return True if the string is a lowercase string, False otherwise. A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
isnumeric(self, /) Return True if the string is a numeric string, False otherwise. A string is numeric if all characters in the string are numeric and there is at least one character in the string.
isprintable(self, /) Return True if the string is printable, False otherwise. A string is printable if all of its characters are considered printable in repr() or if it is empty.
isspace(self, /) Return True if the string is a whitespace string, False otherwise. A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
istitle(self, /) Return True if the string is a title-cased string, False otherwise. In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
isupper(self, /) Return True if the string is an uppercase string, False otherwise. A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
join(self, iterable, /) Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string. Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
ljust(self, width, fillchar=' ', /) Return a left-justified string of length width. Padding is done using the specified fill character (default is a space).
lower(self, /) Return a copy of the string converted to lowercase.
lstrip(self, chars=None, /) Return a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead.
maketrans(...) Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
partition(self, sep, /) Partition the string into three parts using the given separator. This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
removeprefix(self, prefix, /) Return a str with the given prefix string removed if present. If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
removesuffix(self, suffix, /) Return a str with the given suffix string removed if present. If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
replace(self, old, new, count=-1, /) Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. If the optional argument count is given, only the first count occurrences are replaced.
rfind(...) S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
rindex(...) S.rindex(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.
rjust(self, width, fillchar=' ', /) Return a right-justified string of length width. Padding is done using the specified fill character (default is a space).
rpartition(self, sep, /) Partition the string into three parts using the given separator. This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
rsplit(self, /, sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit. Splits are done starting at the end of the string and working to the front.
rstrip(self, chars=None, /) Return a copy of the string with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
split(self, /, sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.
splitlines(self, /, keepends=False) Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.
startswith(...) S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
strip(self, chars=None, /) Return a copy of the string with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
swapcase(self, /) Convert uppercase characters to lowercase and lowercase characters to uppercase.
title(self, /) Return a version of the string where each word is titlecased. More specifically, words start with uppercased characters and all remaining cased characters have lower case.
translate(self, table, /) Replace each character in the string using the given translation table. table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
upper(self, /) Return a copy of the string converted to uppercase.
zfill(self, width, /) Pad a numeric string with zeros on the left, to fill a field of the given width. The string is never truncated.
Typed version of the return of open() in text mode.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: ~AnyStr) -> int
writelines(self, lines: List[~AnyStr]) -> None
buffer = <property object at 0x7f0567898d10>
closed = <property object at 0x7f0567898a90>
encoding = <property object at 0x7f0567898d60>
errors = <property object at 0x7f0567898e00>
line_buffering = <property object at 0x7f0567898e50>
mode = <property object at 0x7f05678989f0>
name = <property object at 0x7f0567898a40>
newlines = <property object at 0x7f0567898ea0>
Type variable. Usage:: T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well 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) -> List[T]: '''Return a list containing n references to x.''' return [x]*n def longest(x: A, y: A) -> A: '''Return the longest of two strings.''' return x if len(x) >= len(y) else y The latter example's signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str. At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables. Type variables can be introspected. e.g.: T.__name__ == 'T' T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes) Note that only type variables defined in global scope can be pickled.
<attribute '__doc__' of 'wrapper_descriptor' objects>
Wrapper namespace for IO generic classes.
Typed version of the return of open() in binary mode.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: Union[bytes, bytearray]) -> int
writelines(self, lines: List[~AnyStr]) -> None
closed = <property object at 0x7f0567898a90>
mode = <property object at 0x7f05678989f0>
name = <property object at 0x7f0567898a40>
Generic base class for TextIO and BinaryIO. This is an abstract, generic version of the return of open(). NOTE: This does not distinguish between the different possible classes (text vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO and BinaryIO subclasses below capture the distinctions between text vs. binary, which is pervasive in the interface; however we currently do not offer a way to track the other distinctions in the type system.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: ~AnyStr) -> int
writelines(self, lines: List[~AnyStr]) -> None
closed = <property object at 0x7f0567898a90>
mode = <property object at 0x7f05678989f0>
name = <property object at 0x7f0567898a40>
Typed version of the return of open() in text mode.
close(self) -> None
fileno(self) -> int
flush(self) -> None
isatty(self) -> bool
read(self, n: int = -1) -> ~AnyStr
readable(self) -> bool
readline(self, limit: int = -1) -> ~AnyStr
readlines(self, hint: int = -1) -> List[~AnyStr]
seek(self, offset: int, whence: int = 0) -> int
seekable(self) -> bool
tell(self) -> int
truncate(self, size: int = None) -> int
writable(self) -> bool
write(self, s: ~AnyStr) -> int
writelines(self, lines: List[~AnyStr]) -> None
buffer = <property object at 0x7f0567898d10>
closed = <property object at 0x7f0567898a90>
encoding = <property object at 0x7f0567898d60>
errors = <property object at 0x7f0567898e00>
line_buffering = <property object at 0x7f0567898e50>
mode = <property object at 0x7f05678989f0>
name = <property object at 0x7f0567898a40>
newlines = <property object at 0x7f0567898ea0>
Wrapper namespace for re type aliases.
Match = typing.Match A generic version of re.Match.
Pattern = typing.Pattern A generic version of re.Pattern.
NamedTuple(typename, fields=None, /, **kwargs) Typed version of namedtuple. Usage in Python versions >= 3.6:: class Employee(NamedTuple): name: str id: int This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has an extra __annotations__ attribute, giving a dict that maps field names to types. (The field names are also in the _fields attribute, which is part of the namedtuple API.) Alternative equivalent keyword syntax is also accepted:: Employee = NamedTuple('Employee', name=str, id=int) In Python versions <= 3.5 use:: Employee = NamedTuple('Employee', [('name', str), ('id', int)])
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
TypedDict(typename, fields=None, /, *, total=True, **kwargs) A simple typed namespace. 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, where each key is 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 can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports two additional equivalent forms:: Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Usage:: class point2D(TypedDict, total=False): x: int y: int This means that a point2D TypedDict can have any of the keys omitted.A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required. The class syntax is only supported in Python 3.6+, while two other syntax forms work for Python 2.7 and 3.2+
abstractmethod(funcobj) A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ...
cast(typ, val) Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible).
final(f) A decorator to indicate final methods and final classes. Use this decorator 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.
get_args(tp) Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int)
get_origin(tp) Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: get_origin(Literal[42]) is Literal get_origin(int) is None get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list
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.
no_type_check(arg) Decorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the function(s) or class(es) in place.
no_type_check_decorator(decorator) Decorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check.
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
runtime_checkable(cls) Mark a protocol class as a runtime protocol. Such protocol 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 one trick ponies in collections.abc such as Iterable. For example:: @runtime_checkable class Closable(Protocol): def close(self): ... assert isinstance(open('/some/file'), Closable) Warning: this will check only the presence of the required methods, not their type signatures!
AbstractSet = typing.AbstractSet A generic version of collections.abc.Set.
Any = typing.Any Special type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. - All values assumed to be instances of Any. Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance or class checks.
AnyStr = ~AnyStr
AsyncContextManager = typing.AsyncContextManager A generic version of contextlib.AbstractAsyncContextManager.
AsyncGenerator = typing.AsyncGenerator A generic version of collections.abc.AsyncGenerator.
AsyncIterable = typing.AsyncIterable A generic version of collections.abc.AsyncIterable.
AsyncIterator = typing.AsyncIterator A generic version of collections.abc.AsyncIterator.
Awaitable = typing.Awaitable A generic version of collections.abc.Awaitable.
ByteString = typing.ByteString A generic version of collections.abc.ByteString.
CT_co = +CT_co
Callable = typing.Callable Callable type; Callable[[int], str] is a function of (int) -> str. The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or ellipsis; the return type must be a single type. There is no syntax to indicate optional or keyword arguments, such function types are rarely used as callback types.
ChainMap = typing.ChainMap A generic version of collections.ChainMap.
ClassVar = typing.ClassVar 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().
Collection = typing.Collection A generic version of collections.abc.Collection.
Container = typing.Container A generic version of collections.abc.Container.
ContextManager = typing.ContextManager A generic version of contextlib.AbstractContextManager.
Coroutine = typing.Coroutine A generic version of collections.abc.Coroutine.
Counter = typing.Counter A generic version of collections.Counter.
DefaultDict = typing.DefaultDict A generic version of collections.defaultdict.
Deque = typing.Deque A generic version of collections.deque.
Dict = typing.Dict A generic version of dict.
EXCLUDED_ATTRIBUTES = ['__parameters__', '__orig_bases__', '__orig_class__', '_is_protocol', '_is_runtime_protocol', '__abstractmethods__', '__annotations__', '__dict__', '__doc__', '__init__', '__module__', '__new__', '__slots__', '__subclasshook__', '__weakref__', '__class_getitem__', '_MutableMapping__marker']
Final = typing.Final Special typing construct to indicate final names to type checkers. A final 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.
FrozenSet = typing.FrozenSet A generic version of frozenset.
Generator = typing.Generator A generic version of collections.abc.Generator.
Hashable = typing.Hashable A generic version of collections.abc.Hashable.
ItemsView = typing.ItemsView A generic version of collections.abc.ItemsView.
Iterable = typing.Iterable A generic version of collections.abc.Iterable.
Iterator = typing.Iterator A generic version of collections.abc.Iterator.
KT = ~KT
KeysView = typing.KeysView A generic version of collections.abc.KeysView.
List = typing.List A generic version of list.
Literal = typing.Literal Special typing form to define literal types (a.k.a. value types). This form can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals): def validate_simple(data: Any) -> Literal[True]: # always returns True ... MODE = Literal['r', 'rb', 'w', 'wb'] def open_helper(file: str, mode: MODE) -> str: ... open_helper('/some/path', 'r') # Passes type check open_helper('/other/path', 'typo') # Error in type checker Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...], but type checkers may impose restrictions.
Mapping = typing.Mapping A generic version of collections.abc.Mapping.
MappingView = typing.MappingView A generic version of collections.abc.MappingView.
Match = typing.Match A generic version of re.Match.
MutableMapping = typing.MutableMapping A generic version of collections.abc.MutableMapping.
MutableSequence = typing.MutableSequence A generic version of collections.abc.MutableSequence.
MutableSet = typing.MutableSet A generic version of collections.abc.MutableSet.
NoReturn = typing.NoReturn 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.
Optional = typing.Optional Optional type. Optional[X] is equivalent to Union[X, None].
OrderedDict = typing.OrderedDict A generic version of collections.OrderedDict.
Pattern = typing.Pattern A generic version of re.Pattern.
Reversible = typing.Reversible A generic version of collections.abc.Reversible.
Sequence = typing.Sequence A generic version of collections.abc.Sequence.
Set = typing.Set A generic version of set.
Sized = typing.Sized A generic version of collections.abc.Sized.
T = ~T
TYPE_CHECKING = False
T_co = +T_co
T_contra = -T_contra
Tuple = typing.Tuple Tuple type; Tuple[X, Y] is the cross-product type of X and Y. Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
Type = typing.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.
Union = typing.Union Union type; Union[X, Y] means either X or Y. To define a union, use e.g. Union[int, str]. Details: - The arguments must be types and there must be at least one. - None as an argument is a special case and is replaced by type(None). - Unions of unions are flattened, e.g.:: Union[Union[int, str], float] == Union[int, str, float] - Unions of a single argument vanish, e.g.:: Union[int] == int # The constructor actually returns int - Redundant arguments are skipped, e.g.:: Union[int, str, int] == Union[int, str] - When comparing unions, the argument order is ignored, e.g.:: Union[int, str] == Union[str, int] - You cannot subclass or instantiate a union. - You can use Optional[X] as a shorthand for Union[X, None].
VT = ~VT
VT_co = +VT_co
V_co = +V_co
ValuesView = typing.ValuesView A generic version of collections.abc.ValuesView.