GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing mypy.readthedocs.io — Kinds of types - mypy 2.4.1 documentation Kinds of types¶We’ve mostly restricted ourselves to built-in types until now. This section introduces several additional kinds of types. You are likely to need at least some of them to type check any non-trivial programs. Class types¶Every class is also a valid type. Any instance of a subclass is also
compatible with all superclasses – it follows that every value is compatible
with the class A: def f(self) -> int: # Type of self inferred (A) return 2 class B(A): def f(self) -> int: return 3 def g(self) -> int: return 4 def foo(a: A) -> None: print(a.f()) # 3 a.g() # Error: "A" has no attribute "g" foo(B()) # OK (B is a subclass of A) The Any type¶A value with the This should not be confused with the
a: Any = None s: str = '' a = 2 # OK (assign "int" to "Any") s = a # OK (assign "Any" to "str") Declared (and inferred) types are ignored (or erased) at runtime. They are
basically treated as comments, and thus the above code does not
generate a runtime error, even though If you do not define a function return value or argument types, these
default to def show_heading(s) -> None: print('=== ' + s + ' ===') # No static type checking, as s has type Any show_heading(1) # OK (runtime error only; mypy won't generate an error) You should give a statically typed function an explicit def wait(t: float): # Implicit Any return value print('Waiting...') time.sleep(t) if wait(2) > 1: # Mypy doesn't catch this error! ... If we had used an explicit def wait(t: float) -> None: print('Waiting...') time.sleep(t) if wait(2) > 1: # Error: can't compare None and int ... The Note A function without any types in the signature is dynamically
typed. The body of a dynamically typed function is not checked
statically, and local variables have implicit Tuple types¶The type # Use `typing.Tuple` in Python 3.8 and earlier def f(t: tuple[int, str]) -> None: t = 1, 'foo' # OK t = 'foo', 1 # Type check error A tuple type of this kind has exactly a specific number of items (2 in
the above example). Tuples can also be used as immutable,
varying-length sequences. You can use the type def print_squared(t: tuple[int, ...]) -> None: for n in t: print(n, n ** 2) print_squared(()) # OK print_squared((1, 3, 5)) # OK print_squared([1, 2]) # Error: only a tuple is valid Note Usually it’s a better idea to use Note
Callable types (and lambdas)¶You can pass around function objects and bound methods in statically
typed code. The type of a function that accepts arguments from collections.abc import Callable def twice(i: int, next: Callable[[int], int]) -> int: return next(next(i)) def add(i: int) -> int: return i + 1 print(twice(3, add)) # 5 Note Import You can only have positional arguments, and only ones without default
values, in callable types. These cover the vast majority of uses of
callable types, but sometimes this isn’t quite enough. Mypy recognizes
a special form from collections.abc import Callable def arbitrary_call(f: Callable[..., int]) -> int: return f('x') + f(y=2) # OK arbitrary_call(ord) # No static error, but fails at runtime arbitrary_call(open) # Error: does not return an int arbitrary_call(1) # Error: 'int' is not callable In situations where more precise or complex types of callbacks are necessary one can use flexible callback protocols. Lambdas are also supported. The lambda argument and return value types cannot be given explicitly; they are always inferred based on context using bidirectional type inference: l = map(lambda x: x + 1, [1, 2, 3]) # Infer x as int and l as list[int] If you want to give the argument or return value types explicitly, use an ordinary, perhaps nested function definition. Callables can also be used against type objects, matching their
from collections.abc import Callable class C: def __init__(self, app: str) -> None: pass CallableType = Callable[[str], C] def class_or_callable(arg: CallableType) -> None: inst = arg("my_app") reveal_type(inst) # Revealed type is "C" This is useful if you want Union types¶Python functions often accept values of two or more different types. You can use overloading to represent this, but union types are often more convenient. Use You can use an def f(x: int | str) -> None: x + 1 # Error: str + int is not valid if isinstance(x, int): # Here type of x is int. x + 1 # OK else: # Here type of x is str. x + 'a' # OK f(1) # OK f('x') # OK f(1.1) # Error Note Operations are valid for union types only if they are valid for every
union item. This is why it’s often necessary to use an Python 3.9 and older only partially support this syntax. Instead, you can
use the legacy from typing import Union def f(x: Union[int, str]) -> None: ... It is also possible to use the new syntax with versions of Python where it
isn’t supported by the runtime with some limitations, if you use
from __future__ import annotations def f(x: int | str) -> None: # OK on Python 3.7 and later ... Optional types and the None type¶You can use def strlen(s: str) -> int | None: if not s: return None # OK return len(s) def strlen_invalid(s: str) -> int: if not s: return None # Error: None not compatible with int return len(s) You can also use the from typing import Optional def strlen(s: str) -> Optional[int]: ... Most operations will not be allowed on unguarded def my_inc(x: int | None) -> int: return x + 1 # Error: Cannot add None and int Instead, an explicit def my_inc(x: int | None) -> int: if x is None: return 0 else: # The inferred type of x is just int here. return x + 1 Mypy will infer the type of Other supported checks for guarding against a def concat(x: str | None, y: str | None) -> str | None: if x is not None and y is not None: # Both x and y are not None here return x + y else: return None Sometimes mypy doesn’t realize that a value is never class Resource: path: str | None = None def initialize(self, path: str) -> None: self.path = path def read(self) -> str: # We require that the object has been initialized. assert self.path is not None with open(self.path) as f: # OK return f.read() r = Resource() r.initialize('/foo/bar') r.read() When initializing a variable as class Resource: path: str | None = None ... This also works for attributes defined within methods: class Counter: def __init__(self) -> None: self.count: int | None = None Often it’s easier to not use any initial value for an attribute.
This way you don’t need to use an optional type and can avoid class Container: items: list[str] # No initial value Mypy generally uses the first assignment to a variable to
infer the type of the variable. However, if you assign both a def f(i: int) -> None: n = None # Inferred type 'int | None' because of the assignment below if i > 0: n = i ... Sometimes you may get the error “Cannot determine type of <something>”. In this
case you should add an explicit Note
Note The Python interpreter internally uses the name Note The type Type aliases¶In certain situations, type names may end up being long and painful to type, especially if they are used frequently: def f() -> list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]: ... When cases like this arise, you can define a type alias by simply assigning the type to a variable (this is an implicit type alias): AliasType = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]] # Now we can use AliasType in place of the full name: def f() -> AliasType: ... Note A type alias does not create a new type. It’s just a shorthand notation for another type – it’s equivalent to the target type except for generic aliases. Python 3.12 introduced the type AliasType = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]] # Now we can use AliasType in place of the full name: def f() -> AliasType: ... There can be confusion about exactly when an assignment defines an implicit type alias – for example, when the alias contains forward references, invalid types, or violates some other restrictions on type alias declarations. Because the distinction between an unannotated variable and a type alias is implicit, ambiguous or incorrect type alias declarations default to defining a normal variable instead of a type alias. Aliases defined using the
There is also use an older syntax for defining explicit type aliases (PEP 613): from typing import TypeAlias AliasType: TypeAlias = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]] Named tuples¶Mypy recognizes named tuples and can type check code that defines or uses them. In this example, we can detect code trying to access a missing attribute: Point = namedtuple('Point', ['x', 'y']) p = Point(x=1, y=2) print(p.z) # Error: Point has no attribute 'z' If you use from typing import NamedTuple Point = NamedTuple('Point', [('x', int), ('y', int)]) p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int" Python 3.6 introduced an alternative, class-based syntax for named tuples with types: from typing import NamedTuple class Point(NamedTuple): x: int y: int p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int" Note You can use the raw For example, it can be useful for deserialization: def deserialize_named_tuple(arg: NamedTuple) -> Dict[str, Any]: return arg._asdict() Point = namedtuple('Point', ['x', 'y']) Person = NamedTuple('Person', [('name', str), ('age', int)]) deserialize_named_tuple(Point(x=1, y=2)) # ok deserialize_named_tuple(Person(name='Nikita', age=18)) # ok # Error: Argument 1 to "deserialize_named_tuple" has incompatible type # "Tuple[int, int]"; expected "NamedTuple" deserialize_named_tuple((1, 2)) Note that this behavior is highly experimental, non-standard, and may not be supported by other type checkers and IDEs. The type of class objects¶(Freely after PEP 484: The type of class objects.) Sometimes you want to talk about class objects that inherit from a
given class. This can be spelled as For example, assume the following classes: class User: # Defines fields like name, email class BasicUser(User): def upgrade(self): """Upgrade to Pro""" class ProUser(User): def pay(self): """Pay bill""" Note that Here’s a function that creates an instance of one of these classes if you pass it the right class object: def new_user(user_class): user = user_class() # (Here we could write the user object to a database) return user How would we annotate this function? Without the ability to parameterize def new_user(user_class: type) -> User: # Same implementation as before This seems reasonable, except that in the following example, mypy
doesn’t see that the buyer = new_user(ProUser) buyer.pay() # Rejected, not a method on User However, using the def new_user[U: User](user_class: type[U]) -> U: # Same implementation as before Here is the example using the legacy syntax (Python 3.11 and earlier): U = TypeVar('U', bound=User) def new_user(user_class: type[U]) -> U: # Same implementation as before Now mypy will infer the correct type of the result when we call
beginner = new_user(BasicUser) # Inferred type is BasicUser beginner.upgrade() # OK Note The value corresponding to For more details about Generators¶A basic generator that only yields values can be succinctly annotated as having a return
type of either def squares(n: int) -> Iterator[int]: for i in range(n): yield i * i A good rule of thumb is to annotate functions with the most specific return
type possible. However, you should also take care to avoid leaking implementation
details into a function’s public API. In keeping with these two principles, prefer
If you want your generator to accept values via the def echo_round() -> Generator[int, float, str]: sent = yield 0 while sent >= 0: sent = yield round(sent) return 'Done' Note that unlike many other generics in the typing module, the If you do not plan on receiving or returning values, then set the def squares(n: int) -> Generator[int, None, None]: for i in range(n): yield i * i This is slightly different from using |
| You are visitor 01402639 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |