简体   繁体   English

isinstance 不导入候选人

[英]isinstance without importing candidates

We have a function which takes a variety of different types of input: a function, a string, a compiled regular expression, a Hamcrest Matcher<\/a> , and filters a list appropriately based on the type of the input.我们有一个函数,它接受各种不同类型的输入:一个函数、一个字符串、一个编译的正则表达式、一个Hamcrest 匹配器<\/a>,并根据输入的类型适当地过滤一个列表。

We're currently using isinstance(our_filter, hamcrest.matcher.Matcher)<\/code> , but this requires us to require Hamcrest to be installed.我们目前正在使用isinstance(our_filter, hamcrest.matcher.Matcher)<\/code> ,但这需要我们安装 Hamcrest。

We're considering using string matches on inspect.getmro(type(POSSIBLE_MATCHER))<\/code> ;我们正在考虑在inspect.getmro(type(POSSIBLE_MATCHER))<\/code>上使用字符串匹配; but this feels unclean.但这感觉不干净。 There might also be options with try<\/code> \/ except<\/code> around the import statement.在 import 语句周围可能还有try<\/code> \/ except<\/code>选项。

What's the best approach?最好的方法是什么?


With help from @dblslash, this is the best I've got so far:在@dblslash 的帮助下,这是迄今为止我得到的最好的:

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

"

恕我直言,使用type(POSSIBLE_MATCHER).__name__是一种相当优雅的类型检查解决方案,而无需导入模块。

If you want to cater for inheritance, using type(POSSIBLE_MATCHER).__name__ will not cut it.如果你想迎合继承,使用type(POSSIBLE_MATCHER).__name__不会削减它。 You could then check against all types in the inheritance chain:然后,您可以检查继承链中的所有类型:

class_string in [t.__name__ for t in type(POSSIBLE_MATCHER).__mro__]

even though this is a quite old question, I thought I'll share my solution for this:尽管这是一个很老的问题,但我想我会为此分享我的解决方案:

  • use a conditional import and set a flag to check if the import was successful before isinstance() !使用条件导入并设置一个标志来检查导入是否在isinstance()之前成功! (after all if the module cannot be imported isinstance should always return False ) (毕竟如果模块不能被导入isinstance应该总是返回False

eg something like this:例如这样的:

try:
    import somemodule

    _import_OK = True
except ImportError:
    _import_OK = False


# and then later in the code:
if _import_OK:
    q = isinstance(x, somemodule.something)
else
    q = False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM