[英]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 的信息?
注意:對這個問題的回答表明,至少可以訪問參數類型提示上的函數自省:
我想知道這些提示是否也可用於在運行時動態強制類型。
在某些情況下,使用外部庫 - 答案是肯定的。 參見下文。
如果您擁有的實際用例像您的C
類一樣簡單,我會去使用數據類和像 dacite 這樣的庫。 您將無法創建 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)
d2 = {'a':'3'}
c2: C = from_dict(C,d2)
輸出
C(a=3)
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.