[英]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>,并根据输入的类型适当地过滤一个列表。
What's the best approach?最好的方法是什么?
With help from @dblslash, this is the best I've got so far:在@dblslash 的帮助下,这是迄今为止我得到的最好的:
"
恕我直言,使用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:尽管这是一个很老的问题,但我想我会为此分享我的解决方案:
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.