【发布时间】:2021-10-23 14:52:36
【问题描述】:
是否可以在运行时检查参数类型提示?我想以与 pureconfig 和 HOCON 配置文件的 Scala 案例类类似的方式使用 Python 数据类。也就是说,我想要一些可选参数,但需要在另一个类构造函数中检查它们。但是,如果参数是可选的,我不知道如何获得。
from dataclasses import dataclass
from typing import Optional
@dataclass
class Params:
x: int
y: int
z: Optional[int] = None
params = Params(x=2, y=3)
假设我想在某处使用数据类Params。如果我检查z,我会得到NoneType。如果我知道这一点,也许我可以绕过任何错误。
# just some example code
if z is None and z is not Optional (not sure if or how to check this):
raise ValueError("z must be specified as an integer")
if z is None and z is optional:
return x ** 2 + y ** 2
elif z is not None:
return x ** 2 + y ** 2 + z ** 2
【问题讨论】:
-
这能回答你的问题吗? How to get class variables and type hints?
-
@mkrieger1 谢谢。明天我会详细看看这个。
标签: python python-typing python-dataclasses