2 ms·
Python's type annotation system has this feature too: from typing import NewType UserId = NewType('UserId', str) user_id: UserId user_id = "
by nerdponx 4y ago
Python's type annotation system has this feature too:
from typing import NewType
UserId = NewType('UserId', str)
user_id: UserId
user_id = "abc" # Type check error
user_id = UserId("abc") # OK
# At runtime, a NewType is the identity function
s1: str = "abc"
s2: UserId = UserId(s1)
assert s1 is s2
Docs: https://docs.python.org/3/library/typing.html#newtype https://docs.python.org/3/library/typing.html#newtype
Runtime: https://tio.run/##TU49D4JADN37K544CIkLupk4OBoTXXQ2CKdcDHeXtsTw6/GQoHZp@9r3ETqtvVv3/Z19A@2CdQ/YJnhWHM3r3AVDdBHD@wrbCUkXI7JYQpQzojauV1ttMOJfIFKS4lYm@NYcgwDK2pRPGGbPf78jO/1QsuH3dCCaY6fg1qltzBLFlAFWoHVslYkn7XBvXanWO5J8M8SavElWU66fheQZFRJnheSDlKyIAlunaXI6zJKs798 https://tio.run/##TU49D4JADN37K544CIkLupk4OBoTXXQ2CKdcDHeXts...
Type checking: https://mypy-play.net/?mypy=latest&python=3.10&flags=show-error-codes%2Cstrict&gist=2f9be920806f100b1654770dca7d3639 https://mypy-play.net/?mypy=latest&python=3.10&flags=show-er...