I noticed that TypedDict
seems to let you pass any arguments to it which is not great.
class X(TypedDict):
id: int
obj1 = X(id=4)
print(obj1)
# {'obj1': 1}
obj2 = X(id=4, thing=3)
print(obj2)
# {'obj1': 1, 'thing': 3} # bad!
I guess this is since TypedDict only works at the type checker level.
But if I still wanted to prevent this happening during runtime, what is the alternative to using a TypedDict?
CodePudding user response:
It is possible to use mypy package.
sudo pip3.9 install mypy
rehash
cat typedDict_ex.py
#!/usr/bin/python3.9
from typing import TypedDict
class X(TypedDict):
id: int
obj1 = X(id=4)
print(obj1)
# {'obj1': 1}
obj2 = X(id=4, thing=3)
print(obj2)
# {'obj1': 1, 'thing': 3} # bad!
mypy typedDict_ex.py
typedDict_ex.py:10: error: Extra key "thing" for TypedDict "X"
Found 1 error in 1 file (checked 1 source file)
CodePudding user response:
Type safety in current versions of Python is not achieved at runtime, but through the use of a static ahead-of-execution analysis with mypy
This is true also for dataclasses
, which have a similar scope as TypedDict
.
If you want to enforce type safety at runtime, this must be done explicitly, e.g.:
class Foo:
def __init__(self, *, bar):
if isinstance(bar, int):
self.bar = bar
else:
raise TypeError
Foo(bar=1)
# <__main__.Foo at 0x7f5400f5c730>
Foo(bar="1")
# TypeError
Foo(baz=1)
# TypeError
or similar.