isinstance没有导入候选人

Dra*_*ave 12 python class hamcrest inspect isinstance

我们有一个函数,它接受各种不同类型的输入:函数,字符串,编译的正则表达式,Hamcrest匹配器,并根据输入的类型适当地过滤列表.

我们目前正在使用isinstance(our_filter, hamcrest.matcher.Matcher),但这需要我们安装Hamcrest.

我们正在考虑使用字符串匹配inspect.getmro(type(POSSIBLE_MATCHER)); 但这感觉不洁净.import语句可能还有try/ except周围的选项.

什么是最好的方法?


在@dblslash的帮助下,这是迄今为止我所做的最好的:

[x.__module__+"."+x.__name__ for x in inspect.getmro(type(POSSIBLE_MATCHER))] ['hamcrest.core.core.isequal.IsEqual', 'hamcrest.core.base_matcher.BaseMatcher', 'hamcrest.core.matcher.Matcher', 'hamcrest.core.selfdescribing.SelfDescribing', '__builtin__.object']

bwi*_*ind 16

使用type(POSSIBLE_MATCHER).__name__IMHO是一种相当优雅的类型检查解决方案,无需导入模块.


jnn*_*nns 7

如果你想满足继承的需要,使用type(POSSIBLE_MATCHER).__name__并不会减少它。然后您可以检查继承链中的所有类型:

class_string in [t.__name__ for t in type(POSSIBLE_MATCHER).__mro__]
Run Code Online (Sandbox Code Playgroud)