Wrangling the typing PEPs
Wrangling the typing PEPs
Posted Dec 16, 2021 17:50 UTC (Thu) by anselm (subscriber, #2796)In reply to: Wrangling the typing PEPs by mb
Parent article: Wrangling the typing PEPs
Does Python have the possibility to specify a Procotol as "type" instead of nailing down the type to some specific ones?
Yes, this is explained in PEP-544, which deals with “duck typing”.
There's List, which means object with list procotol, as far as I understand it. But is there something similar for paths?
The os module implements PathLike as an “abstract base class” for classes that implement path-like behaviour (such as pathlib.Path). Basically this means that such classes support the __fspath__() method, which is supposed to return a representation of the object that is a str suitable to use as a file system path. If you wanted to say that a function accepts a parameter that is either a str to begin with, or a PathLike object, you could define it as
from os import fspath, PathLike def do_something_with_path(path: str | PathLike) -> …: … f = open(fspath(path)) …(where os.fspath(s) will return s outright if s is of type str, or else s.__fspath__()). Of course you could also define a type variable like
PathOrStr = TypeVar('PathOrStr', str, PathLike)and then simply use this as
def do_something_with_path(path: PathOrStr) -> ...: …
Can the developer create new such types for his own protocols?
Absolutely. See here.