問題描述
我正在嘗試編寫一個函數(shù)裝飾器,它使用 Python 3.6 類型提示來檢查參數(shù)字典是否尊重類型提示,如果沒有明確說明問題,則引發(fā)錯誤,以用于 HTTP API.
I'm trying to write a function decorator that uses Python 3.6 type hints to check that a dictionary of arguments respects the type hints and if not raise an error with a clear description of the problem, to be used for HTTP APIs.
問題是當函數(shù)有一個使用 Union
類型的參數(shù)時,我無法在運行時檢查變量.
The problem is that when the function has a parameter using the Union
type I can't check a variable against it at runtime.
比如我有這個功能
from typing import Union
def bark(myname: str, descr: Union[int, str], mynum: int = 3) -> str:
return descr + myname * mynum
我能做到:
isinstance('Arnold', bark.__annotations__['myname'])
但不是:
isinstance(3, bark.__annotations__['descr'])
因為 Union
不能與 isinstance
或 issubclass
一起使用.
Because Union
cannot be used with isinstance
or issubclass
.
我找不到使用類型對象檢查它的方法.我嘗試自己實施檢查,但是當 bark.__annotations__['descr']
在 REPL 中顯示為 typing.Union[int, str]
我不能在運行時訪問類型列表,如果不使用檢查 bark.__annotations__['descr'].__repr__()
的丑陋技巧.
I couldn't find a way to check it using the type object.
I tried to implement the check by myself but while bark.__annotations__['descr']
is shown as typing.Union[int, str]
in the REPL I can't access the list of the types at runtime, if not using the ugly hack of examining bark.__annotations__['descr'].__repr__()
.
是否有適當?shù)姆椒▉碓L問這些信息?還是故意讓它在運行時不易訪問?
Is there a proper way to access this information? Or is it deliberately intended to not be easily accessible at runtime?
推薦答案
你可以使用 Union
的 __args__
屬性,它包含一個 tuple
可能的內(nèi)容:
You could use the __args__
attribute of Union
which holds a tuple
of the "possible contents:
>>> from typing import Union
>>> x = Union[int, str]
>>> x.__args__
(int, str)
>>> isinstance(3, x.__args__)
True
>>> isinstance('a', x.__args__)
True
__args__
參數(shù)沒有記錄,因此它可能被認為是弄亂了實現(xiàn)細節(jié)",但它似乎比解析 repr
更好.
The __args__
argument is not documented so it could be considered "messing with implementation details" but it seems like a better way than parsing the repr
.
這篇關(guān)于在 Python 3.6 中運行時根據(jù)聯(lián)合類型檢查變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!