Differences between revisions 4 and 6 (spanning 2 versions)
Revision 4 as of 2023-01-07 00:59:04
Size: 7118
Comment:
Revision 6 as of 2023-01-07 01:41:03
Size: 8889
Comment:
Deletions are marked like this. Additions are marked like this.
Line 19: Line 19:
'''`Any`''' satisfies all type checking, which can be useful for making things 'just work'. `Any` satisfies all type checking, which can be useful for making things 'just work'.



=== AnyStr ===

If a function can take either a normal string or a byte string (`b""`), annotate the argument with `AnyStr`.

This will satisfy type checkers while still catching issues relating to the combination of these incompatible types

{{{
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

# pass
concat("foo", "bar")

# pass
concat(b"foo", b"bar")

# fail
concat("foo", b"bar")
Line 31: Line 52:
To annotate an argument or return value that must be one of a set of literal values, use '''`Literal`'''. To annotate an argument or return value that must be one of a set of literal values, use `Literal`.
Line 53: Line 74:
...use '''`LiteralString`'''. As an example, consider SQL templating functions. ...use `LiteralString`. As an example, consider SQL templating functions.
Line 118: Line 139:
To annotate an argument that can also be `None`, use '''`Optional`'''. To annotate an argument that can also be `None`, use `Optional`.
Line 139: Line 160:
To annotate an argument that can be multiple types, use '''`Union`'''. To annotate an argument that can be multiple types, use `Union`.
Line 155: Line 176:
See also the [[Python/Builtins#Operators|union operator]] (`|`). See also the [[Python/Builtins#UnionOperator|union operator]] (`|`).
Line 188: Line 209:
=== Self ===

For class methods that return an instance of the class, use `Self`. This is superior to using forward references because subclasses will automatically have the correct annotation.

{{{
from typing import Self

class Foo:
    def return_self(self) -> Self:
        return self
}}}


Line 190: Line 225:
Functions like `isinstance` function as a type guard; subsequent conditional lines are checked knowing that a value has passed the guard and is of a contrained type.

Custom type guard functions can be written and annotated with '''`TypeGuard`'''. If the function returns `True`, then the corresponding value is of a constrained type.
Functions like `isinstance` act as '''type guards'''. Type checkers understand that subsequent conditional logic will only be called if the value is of a known, constrained type.

Custom type guards can be written and annotated with `TypeGuard[T]`. If the function returns `True`, then the value is of type `T`.
Line 211: Line 246:
=== Functions ===



==== Never ====

If there is a function that should never be called, annotate the argument with '''`Never`'''.
=== ClassVar ===

If there is a class attribute that should never be set on an instance, annotate with `ClassVar`.

{{{
from typing import ClassVar

class Quadruped:
    feet: ClassVar[int] = 4

cat = Quadruped("cat")

# fail
cat.feet = 3
}}}



=== Final ===

If there is a constant that should never be changed, annotate with `Final`.

{{{
from typing import Final

MAX_CONN: Final[int] = 1

# fail
MAX_CONN += 1
}}}



=== Never ===

If there is a function that should never be called, annotate the argument with `Never`.
Line 242: Line 306:
==== NoReturn ==== === NoReturn ===
Line 245: Line 309:



=== Constants ===



==== Final ====

If there is a constant that should never be changed, annotate with '''`Final`'''.

{{{
from typing import Final

MAX_CONN: Final[int] = 1

# fail
MAX_CONN += 1
}}}



=== Classes ===



==== ClassVar ====

If there is a class attribute that should never be set on an instance, annotate with '''`ClassVar`'''.

{{{
from typing import ClassVar

class Quadruped:
    feet: ClassVar[int] = 4

cat = Quadruped("cat")

# fail
cat.feet = 3
}}}



==== Self ====

For class methods that return an instance of the class, use '''`Self`'''. This is superior to using forward references because subclasses will automatically have the correct annotation.

{{{
from typing import Self

class Foo:
    def return_self(self) -> Self:
        return self
}}}
Line 332: Line 341:
== Generics ==

To annotate a generic type, use `TypeVar`.
== Protocols ==

`Protocol` is a base class for '''protocols'''.

{{{
from typing import Protocol

class SomeProtocol(Protocol):
    def meth(self) -> int:
        ...

class A:
    def meth(self) -> int:
        return 0

class B:
    def meth(self) -> int:
        return 1

def func(c: SomeProtocol) -> int:
    return c.meth()

# pass
func(A())

# pass
func(B())
}}}

Protocol classes can be [[Python/Typing#Generic_Types|generic]] as well.

{{{
from typing import TypeVar, Protocol

T = TypeVar('T')

class GenericProtocol(Protocol[T]):
    def meth(self) -> T:
        ...
}}}

----




== Generic Types ==

To annotate a '''generic type''', use `TypeVar`.
Line 346: Line 401:
There are additional type constructs for '''variadic generics'''.

For example, to constrain the type of the first or last value in a tuple while leaving others alone, use `TypeVarTuple`.

{{{
from typing import TypeVar, TypeVarTuple

T = TypeVar('T')
Ts = TypeVarTuple('Ts')

def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
    return (*tup[1:], tup[0])
}}}

`TypeVarTuple` is only valid when used with the [[Python/Builtins#ExpansionOperator|expansion operator]].

{{{
from typing import TypeVar, TypeVarTuple

T = TypeVar('T')
Ts = TypeVarTuple('Ts')

# fail
x: tuple[Ts]

# pass
x: tuple[*Ts]
}}}

In the above context, `*Ts` would be equivalent to using `Unpack[Ts]`. `Unpack` exists because the expansion operator ''formerly'' could not be used in this way. Do not use `Unpack` in Python 3.11+.

Python Typing

The typing and typing_extensions modules support the type annotation system in the Python language.

The type annotation system has evolved rapidly with multiple instances of breaking changes. For an overview of the entire system, see Type Annotation.


Primitive Types

Any

Any satisfies all type checking, which can be useful for making things 'just work'.

AnyStr

If a function can take either a normal string or a byte string (b""), annotate the argument with AnyStr.

This will satisfy type checkers while still catching issues relating to the combination of these incompatible types

def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

# pass
concat("foo", "bar")

# pass
concat(b"foo", b"bar")

# fail
concat("foo", b"bar")



=== Callable ===

Do not use `typing.Callable[...]` in Python 3.9+; instead use `collections.abc.Callable[...]`.



=== Literal ===

To annotate an argument or return value that must be one of a set of literal values, use `Literal`.

{{{
from typing import Literal

def true() -> Literal[True]:
    return True

def open_helper(file: str, mode: Literal['r', 'rb', 'w', 'wb']) -> None:
    pass

LiteralString

To annotate a string argument or return value that must one of...

  • a literal string value
  • a string value annotated as Literal or LiteralString

  • a combination of the above

...use LiteralString. As an example, consider SQL templating functions.

from typing import LiteralString

def run_query(sql: LiteralString) -> None
    pass

def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
    # pass, because is a literal string
    run_query("SELECT * FROM students")

    # pass, because is a value annotated as a LiteralString
    run_query(literal_string)

    # pass, because is a combination of a literal string and a value annotated as a LiteralString
    run_query("SELECT * FROM " + literal_string)

    run_query(arbitrary_string)  # type checker error
    run_query(  # type checker error
        f"SELECT * FROM students WHERE name = {arbitrary_string}"
    )

This adds a degree of safety by way of the type checker.

The following str methods all preserve LiteralString annotation.

  • capitalize

  • casefold

  • center

  • expandtabs

  • format

  • join

  • ljust

  • lower

  • lstrip

  • partition

  • removeprefix

  • removesuffix

  • replace

  • rjust

  • rpartition

  • rsplit

  • rstrip

  • split

  • splitlines

  • strip

  • swapcase

  • title

  • upper

  • zfill

  • __add__

  • __iter__

  • __mod__

  • __mul__

  • __repr__

  • __rmul__

  • __str__

  • f-strings

Optional

To annotate an argument that can also be None, use Optional.

from typing import Optional

def int_or_none(arg: Optional[int]) -> None:
    if arg is not None:
        # type checkers understand type guards; `arg` is checked as an `int` here
        arg += 1

Tuple

Do not use typing.Tuple[...] in Python 3.9+; instead use the built-in tuple[...].

Union

To annotate an argument that can be multiple types, use Union.

from typing import Union

def int_or_str(arg: Union[int, str]) -> None:
    if isinstance(arg, int):
        # type checkers understand type guards; `arg` is checked as an `int` here
        arg += 1
    else:
        # type checkers also infer that `arg` is a `str` here
        arg += "1"

If the argument can be either a type or None, consider Optional.

See also the union operator (|).


Annotations for Type Hints

The following annotations are mostly useful for visual hints in IDEs.

Annotated

from typing import Annotated

SmallInt = Annotated[int, ValueRange(0, 9)]


Annotations for Annotations

The following annotations are mostly useful for supporting annotations.

Self

For class methods that return an instance of the class, use Self. This is superior to using forward references because subclasses will automatically have the correct annotation.

from typing import Self

class Foo:
    def return_self(self) -> Self:
        return self

TypeGuard

Functions like isinstance act as type guards. Type checkers understand that subsequent conditional logic will only be called if the value is of a known, constrained type.

Custom type guards can be written and annotated with TypeGuard[T]. If the function returns True, then the value is of type T.

from typing import TypeGuard

def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)


Annotations for Logic Checks

The following annotations are mostly useful for causing a type checker to identify issues with program logic. They may be necessary to satisfy the type checker in edge cases.

ClassVar

If there is a class attribute that should never be set on an instance, annotate with ClassVar.

from typing import ClassVar

class Quadruped:
    feet: ClassVar[int] = 4

cat = Quadruped("cat")

# fail
cat.feet = 3

Final

If there is a constant that should never be changed, annotate with Final.

from typing import Final

MAX_CONN: Final[int] = 1

# fail
MAX_CONN += 1

Never

If there is a function that should never be called, annotate the argument with Never.

from typing import Never

def never_call_me(arg: Never) -> None:
    pass

# fail
def do_it_anyway(arg: int | str) -> None:
    never_call_me(arg)

# pass: arg is either int or str so the default case is never reached
def int_or_str(arg: int | str) -> None:
    match arg:
        case int():
            pass
        case str():
            pass
        case _:
            never_call_me(arg)

NoReturn

Do not use NoReturn in Python 3.11+; instead use Never.


Custom Types

To create a custom type, use NewType. Type checkers will treat the custom type as a subclass of the original type, while rejecting passed arguments of the original type.

from typing import NewType

UserId = NewType('UserId', int)

# passes
user_a = get_user_name(UserId(42351))

# fails
user_b = get_user_name(-1)

Given the above example, at runtime, UserId returns a callable that immediately returns the original value. This leads to three properties:

  1. UserId(value) has minimal runtime overhead

  2. an instance of UserId cannot be returned at runtime; UserId(value) immediately evaluates to value

  3. UserId is not subclassable (except by chaining NewType: ProUserId = NewType('ProUserId', UserId))


Protocols

Protocol is a base class for protocols.

from typing import Protocol

class SomeProtocol(Protocol):
    def meth(self) -> int:
        ...

class A:
    def meth(self) -> int:
        return 0

class B:
    def meth(self) -> int:
        return 1

def func(c: SomeProtocol) -> int:
    return c.meth()

# pass
func(A())

# pass
func(B())

Protocol classes can be generic as well.

from typing import TypeVar, Protocol

T = TypeVar('T')

class GenericProtocol(Protocol[T]):
    def meth(self) -> T:
        ...


Generic Types

To annotate a generic type, use TypeVar.

from collections.abc import Sequence
from typing import TypeVar

T = TypeVar('T')

def first(l: Sequence[T]) -> T:
    return l[0]

There are additional type constructs for variadic generics.

For example, to constrain the type of the first or last value in a tuple while leaving others alone, use TypeVarTuple.

from typing import TypeVar, TypeVarTuple

T = TypeVar('T')
Ts = TypeVarTuple('Ts')

def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
    return (*tup[1:], tup[0])

TypeVarTuple is only valid when used with the expansion operator.

from typing import TypeVar, TypeVarTuple

T = TypeVar('T')
Ts = TypeVarTuple('Ts')

# fail
x: tuple[Ts]

# pass
x: tuple[*Ts]

In the above context, *Ts would be equivalent to using Unpack[Ts]. Unpack exists because the expansion operator formerly could not be used in this way. Do not use Unpack in Python 3.11+.


CategoryRicottone

Python/Typing (last edited 2023-04-20 14:07:06 by DominicRicottone)