类型检查:一个可迭代类型,但不是字符串

2024-09-26 22:44:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

如果objstr以外的可iterable类型,则返回True。但是,如果objstr或不可iterable类型,则返回False

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

我想列出除str之外的所有其他iterable类型,如下所示:

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

但问题是,这种方法将丢失未显式列出的任何其他iterable类型。

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


Tags: 方法函数fromimportobj类型returndef
2条回答

我用这段代码检查它,它在Python 2和Python 3中运行良好

from __future__ import unicode_literals
import types
import collections

var = ["a", "b", "c"]
if isinstance(var, collections.Iterable) and \
        not isinstance(var, types.StringTypes):
    return var

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

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

缺点是__iter__不是一种真正的python方法:例如,有些对象可能实现__getitem__,但不是__iter__

在Python 3.x中,strings得到了__iter__属性,从而破坏了这个方法。

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

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

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

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

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

相关问题 更多 >

    热门问题