我正在尝试在Python中定义类型化的字典。我已经编写了以下代码段,但我想知道是否有更好的方法可以实现相同的目标。我正在使用defaultdict
,但可以根据需要随时将其更改为dict
。
from collections import defaultdict
class typed_dict(defaultdict):
def __init__(self, key_type, val_type, *args, **kwargs):
self.key_type = key_type
if type(val_type) == type(lambda: 1):
self.val_type = type(val_type())
else:
self.val_type = val_type
super(typed_dict, self).__init__(val_type, *args, **kwargs)
def __getitem__(self, k):
try:
assert type(k) == self.key_type
return super(typed_dict, self).__getitem__(k)
except AssertionError:
print('key mismatch, got {}, must be {}'.format(type(k), self.key_type))
def __setitem__(self, k, v):
try:
assert type(k) == self.key_type
assert type(v) == self.val_type
super(typed_dict, self).__setitem__(k, v)
except AssertionError:
print('key or value mismatch, got {}: {}, \
must be {}: {}'.format(type(k), type(v), self.key_type, self.val_type))
d = typed_dict(int, str)
d[1]
d[2] = "two"
d["one"]
d["three"] = 3
d[3] = 3
print(d)
d = typed_dict(int, lambda: '')
d[1]
d[2] = "two"
d["one"]
d["three"] = 3
d[3] = 3
print(d)
import numpy as np
d = typed_dict(int, lambda: np.zeros(2))
d[1]
d[2] = "two"
d[3] = np.array([1,2,3])
print(d)