类型检查:不是字符串的可迭代类型 [英] Type checking: an iterable type that is not a string

查看:51
本文介绍了类型检查:不是字符串的可迭代类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地解释,考虑这个简单的类型检查器函数:

To explain better, consider this simple type checker function:

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

如果objstr 以外的可迭代类型,则返回True.但是,如果 objstr 或不可迭代类型,则返回 False.

If obj is an iterable type other than str, it returns True. However, if obj is a str or a non-iterable type, it returns False.

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

Is there any way to perform the type check more efficiently? I mean, it seems kinda redundant to check the type of obj once to see if it is not a str and then check it again to see if it is iterable.

我想过像这样列出除 str 之外的所有其他可迭代类型:

I thought about listing every other iterable type besides str like this:

return isinstance(obj, (list, tuple, dict,...))

但问题是这种方法会遗漏任何其他未明确列出的可迭代类型.

But the problem is that that approach will miss any other iterable types that are not explicitly listed.

那么……有没有更好的方法,或者我在函数中给出的方法最有效?

So...is there anything better or is the approach I gave in the function the most efficient?

推荐答案

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.

这篇关于类型检查:不是字符串的可迭代类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆