Skip to content

Commit fb71447

Browse files
committed
Apply TR fixes
1 parent 0c83b27 commit fb71447

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

python-mixins/typed_dict.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
def typed_dict(key_type=object, value_type=object):
2+
def class_decorator(cls):
3+
setitem = cls.__setitem__
4+
5+
def __setitem__(self, key, value):
6+
if not isinstance(key, key_type):
7+
raise TypeError(
8+
f"value must be {key_type} but was {type(key)}"
9+
)
10+
11+
if not isinstance(value, value_type):
12+
raise TypeError(
13+
f"value must be {value_type} but was {type(value)}"
14+
)
15+
16+
setitem(self, key, value)
17+
18+
cls.__setitem__ = __setitem__
19+
20+
return cls
21+
22+
return class_decorator
23+
24+
25+
if __name__ == "__main__":
26+
from collections import UserDict
27+
28+
# Enforce str keys and int values:
29+
@typed_dict(str, int)
30+
class Inventory(UserDict):
31+
pass
32+
33+
# Enforce str keys, allow any value type:
34+
@typed_dict(str)
35+
class AppSettings(UserDict):
36+
pass
37+
38+
fruits = Inventory()
39+
fruits["apples"] = 42
40+
41+
try:
42+
fruits["🍌".encode("utf-8")] = 15
43+
except TypeError as ex:
44+
print(ex)
45+
46+
try:
47+
fruits["bananas"] = 3.5
48+
except TypeError as ex:
49+
print(ex)
50+
51+
settings = AppSettings()
52+
settings["host"] = "localhost"
53+
settings["port"] = 8080
54+
settings["debug_mode"] = True
55+
56+
try:
57+
settings[b"binary data"] = "nope"
58+
except TypeError as ex:
59+
print(ex)

0 commit comments

Comments
 (0)