by BeefySwain · 3y ago · 0 comments
Runtime behaviour determination: the stdlib [dataclasses](https://docs.python.org/3/library/dataclasses.html#module-da...)
Dataclasses is notable because it's the only example (I'm aware of) of type hints effecting runtime behavior as part of the stdlib.
Compiler instructions: mypyc was (one of?) the first to do this, but Cython actually supports this natively now, and is much more active than mypyc is last I checked.
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
And that's fine. I wouldn't necessarily change anything here. Annotated gives you the option of approaching things in a different way, though. class Hero(SQLModel, table=True):
id: PrimaryKey[Optional[int]] = None
I have some use cases where the alternative approach is useful, like quantification of class fields or function arguments.FWIW, `typing.NamedTuple` did this in Python 3.5, three years before dataclasses was introduced in 3.7.
class Foo(typing.NamedTuple):
a: int
b: str
f = Foo(a=1, b="hello")
print(f.b) # "hello" Foo = typing.NamedTuple('Foo', [('a', int), ('b', str)])> To add overloaded implementations to the function, use the register() attribute of the generic function, which can be used as a decorator. For functions annotated with types, the decorator will infer the type of the first argument automatically:
That appears to be the only other case.
>>> @dataclasses.dataclass
... class D:
... x: int
...
>>> D('a')
D(x='a') @dataclass
class A:
a: int = 0
b = 1
>>> A(a=1, b=2)
TypeError: __init__() got an unexpected keyword argument 'b'