【问题标题】:Python: parameter type hint during run timePython:运行时的参数类型提示
【发布时间】: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

【问题讨论】:

标签: python python-typing python-dataclasses


【解决方案1】:

见下文。这个想法是使用__post_init__并检查z的注释。取消注释#z: int,看看它是如何工作的。

from dataclasses import dataclass
from typing import Optional


@dataclass
class Params:
    x: int
    y: int
    z: Optional[int] = None
    #z: int

    def __post_init__(self):
        print('post init')
        if self.z is None:
            z_annotation = self.__annotations__['z']
            none_is_ok = False
            args = z_annotation.__dict__.get('__args__')
            if args is not None:
                for entry in args:
                    none_is_ok = entry == type(None)
                    if none_is_ok:
                        break
            if not none_is_ok:
                raise ValueError('z can not be None')


p: Params = Params(3, 5, None)
print(p)

【讨论】:

  • 谢谢,明天我会详细看一下这个答案的评论链接,看看我的目的是什么最好的服务。
  • @dustin 我认为你也应该看看 mypy (mypy.readthedocs.io/en/stable)。它将指向您提到的那些案例
猜你喜欢
  • 2016-05-17
  • 2021-03-23
  • 1970-01-01
  • 2016-01-27
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2012-01-21
相关资源
最近更新 更多