簡體   English   中英

Python:遞歸isinstance檢查

[英]Python: recursive isinstance checking

如何檢查嵌套抽象類的完整類型簽名? 在這個例子中

In [4]: from typing import Sequence

In [5]: IntSeq = Sequence[int]

In [6]: isinstance([1], IntSeq)
Out[6]: True

In [7]: isinstance([1.0], IntSeq)
Out[7]: True

我希望最后一個isinstance調用實際返回False ,而它只檢查參數是否為Sequence 我想過以遞歸方式檢查類型,但IntSeq沒有存儲嵌套類型的公共屬性:

In [8]: dir(IntSeq)
Out[8]: 
['__abstractmethods__',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__extra__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__origin__',
 '__parameters__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__slots__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_abc_cache',
 '_abc_negative_cache',
 '_abc_negative_cache_version',
 '_abc_registry']

因此,獲取嵌套類型似乎並不簡單。 我在文檔中找不到相關信息。

PS我需要這個用於多個調度實現。

更新

感謝Alexander Huszagh和Blender的反饋,我們現在知道Python 3.5中的抽象類(可能)有兩個存儲嵌套類型的屬性: __parameters____args__ 前者存在於Linux(Ubuntu)和Darwin(OS X)之下,但在Linux的情況下它是空的。 后者僅在Linux下可用,並且在OS X下存儲像__parameters__這樣的類型。這種實現細節加起來很混亂。

我看到你正在嘗試使用仍然是臨時的模塊來實現某些功能; 如果你這樣做,你將遇到一個不斷變化的界面。

Blender注意到__parameters__參數保存了類型的參數; 這是真的,直到,我相信3.5.1 在我最新版本的Python( 3.6.0a4+ )的git克隆中, 3.6.0a4+ __parameters__再次保存一個空元組, __args__保存參數, __origin__是其__bases__屬性中的第一個條目:

>>> intSeq = typing.Sequence[int]
>>> intSeq.__args__
(<class 'int'>,)
>>> intSeq.__parameters__
()
>>> intSeq.__origin__
typing.Sequence<+T_co>

因為3.6是打字的時候,根據我從PEP 411理解,保留臨時狀態並進入穩定狀態,這是你應該用來實現你的功能的版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM