且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 19:27:16

python 2.x 中,检查 __iter__ 属性很有帮助(虽然并不总是明智的),因为迭代应该有这个属性,但字符串没有.

In python 2.x, Checking for the __iter__ attribute was helpful (though not always wise), because iterables should have this attribute, but strings did not.

def typecheck(obj): return hasattr(myObj, '__iter__')

缺点是 __iter__ 并不是真正的 Pythonic 方法:例如,某些对象可能实现了 __getitem__ 而不是 __iter__.

The down side was that __iter__ was not a truely Pythonic way to do it: Some objects might implement __getitem__ but not __iter__ for instance.

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

In Python 3.x, strings got the __iter__ attribute, breaking this method.

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

The method you listed is the most efficient truely Pythonic way I know in Python 3.x:

def typecheck(obj): return not isinstance(obj, str) and isinstance(obj, Iterable)

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

There is a much faster (more efficient) way, which is to check __iter__ like in Python 2.x, and then subsequently check str.

def typecheck(obj): return hasattr(obj, '__iter__') and not isinstance(obj, str)

这与 Python 2.x 中的警告相同,但速度要快得多.

This has the same caveat as in Python 2.x, but is much faster.