Cor*_*zin 6 python typing typescript mypy python-dataclasses
TypeScript has a Pick type which can take an existing type and create a new one by picking individual attributes. I would like to have a similar functionality in Python, so for example:
from dataclasses import dataclass
from pick import Pick
@dataclasses.dataclass
class Foo:
x: int
y: float
z: str
Bar = Pick(Foo, ('x', 'y'))
foo = Foo(1, 2.0, '3')
bar = Bar(1, 2.0)
Run Code Online (Sandbox Code Playgroud)
I want this to avoid the problem of partial object population without having to explicitly define many different classes which are really just subsets of a larger one. Ideally, this will be type-safe and recognized by mypy.
我研究了其他解决方案,例如为属性的每个子集定义一个新类,但这产生了太多相似但略有不同的类,使得代码更难以阅读。我还尝试使用一个大类,其中每个字段都是可选的,但这仍然使代码难以阅读,因为我必须推理对象的谱系来判断它是否有某个字段,或者该字段是否为空。
如果还有一种方法可以通过类似的方式添加字段,那就加分了Baz = Add(Foo, {'w': List}); baz(1, 2.0, '3', w=[])