类型检查:不是字符串的可迭代类型

iCo*_*dez 14 python typechecking python-3.x

为了更好地解释,请考虑这种简单的类型检查功能:

from collections import Iterable
def typecheck(obj):
    return not isinstance(obj, str) and isinstance(obj, Iterable)
Run Code Online (Sandbox Code Playgroud)

如果obj是可迭代类型str,则返回True.但是,如果obj是a str或不可迭代类型,则返回False.

有没有办法更有效地执行类型检查?我的意思是,检查obj一次的类型看是否不是a 似乎有点多余str,然后再次检查它以查看它是否可迭代.

我想除了str像这样列出所有其他可迭代类型:

return isinstance(obj, (list, tuple, dict,...))
Run Code Online (Sandbox Code Playgroud)

但问题是该方法将错过任何未明确列出的其他可迭代类型.

那么......有什么更好的,或者我在函数中给出的方法效率最高?

Pi *_*ion 14

python 2.x中,检查__iter__属性是有帮助的(尽管并不总是明智的),因为iterables应该具有此属性,但字符串不具有此属性.

def typecheck(obj): return hasattr(myObj, '__iter__')
Run Code Online (Sandbox Code Playgroud)

__iter__缺点是这不是真正的Pythonic方法:有些对象可能会实现__getitem__但不是__iter__例如.

Python 3.x中,字符串获得了__iter__属性,破坏了这种方法.

您列出的方法是我在Python 3.x中知道的最有效的Pythonic方法:

def typecheck(obj): return not isinstance(obj, str) and isinstance(obj, Iterable)
Run Code Online (Sandbox Code Playgroud)

有一种更快(更有效)的方式,__iter__就像在Python 2.x中检查一样,然后检查str.

def typecheck(obj): return hasattr(obj, '__iter__') and not isinstance(obj, str)
Run Code Online (Sandbox Code Playgroud)

这与Python 2.x中的注意事项相同,但速度要快得多.