python : 使用类型提示动态检查类型

python : using type hints to dynamically check types

python 支持类型提示:

https://docs.python.org/3/library/typing.html

我想知道这些提示是否也可用于在运行时动态强制类型。

例如:

class C:

    def __init__(self):
        self.a : int = 0

    def __str__(self):
        return str(self.a)

    @classmethod
    def get(cls,**kwargs):
        c = cls()
        for k,v  in kwargs.items():
            setattr(c,k,v) 
            # ValueError exception thrown here ?
        return c

attrs = {"a":"a"} # developer wanted an int !
c = C.get(**attrs)
print(c)

简而言之,我想避免在get函数中重新输入属性“a”的类型:

    @classmethod
    def get(cls,**kwargs):
        c = cls()
        for k,v  in kwargs.items():
            if k=="a" and not isinstance(v,int):
                raise ValueError()
            setattr(c,k,v) 
        return c

是否有一种方法可以“重用”构造函数中给出的“a”应该是 int 的信息?

注意:这个问题的答案表明至少对于函数自省参数类型提示是可以访问的:

I was wondering if these hints can also be used to dynamically enforce types during runtime.

在某些情况下和外部库 - 答案是肯定的。阅读下文。

如果您的实际用例像 C class 一样简单,我会去使用数据class 和像英安岩这样的库。您将无法创建 c2,因为您没有传递 int。
所以英安岩设法“看到” a 应该是 int 并引发异常

from dataclasses import dataclass
from dacite import from_dict
@dataclass
class C:
  a:int = 0

d1 = {'a':3}

c1: C = from_dict(C,d1)
print(c1)
print(C.__annotations__)

d2 = {'a':'3'}

c2: C = from_dict(C,d2)

输出

C(a=3)
{'a': <class 'int'>}

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    c2: C = from_dict(C,d2)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/dacite/core.py", line 68, in from_dict
    raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)
dacite.exceptions.WrongTypeError: wrong value type for field "a" - should be "int" instead of value "3" of type "str"