python - Using List/Tuple/etc. from typing vs directly referring type as list/tuple/etc -
what's difference of using list, tuple, etc. typing module:
from typing import tuple def f(points: tuple): return map(do_stuff, points) as opposed referring python's types directly:
def f(points: tuple): return map(do_stuff, points) and when should use 1 on other?
typing.tuple , typing.list generic types; means can specify type contents must be:
def f(points: tuple[float, float]): return map(do_stuff, points) this specifies tuple passed in must contain 2 float values. can't built-in tuple type.
typing.tuple special here in lets specify specific number of elements expected , type of each position. use ellipsis if length not set , type should repeated: tuple[float, ...] describes variable-length tuple floats.
for typing.list , other sequence types specify type elements; list[str] list of strings, of size. note functions should preferentially take type.sequence arguments , typing.list typically used return types; speaking functions take sequence , iterate, when return list, returning specific, mutable sequence type.
you should pick typing generics when not restricting contents. easier add constraint later generic type resulting change smaller.
Comments
Post a Comment