python 如何检查对象是否是命名元组的实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2166818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an object is an instance of a namedtuple?
提问by Sridhar Ratnakumar
How do I check if an object is an instance of a Named tuple?
如何检查对象是否是Named tuple的实例?
采纳答案by Alex Martelli
Calling the functioncollections.namedtuple
gives you a new type that's a subclass of tuple
(and no other classes) with a member named _fields
that's a tuple whose items are all strings. So you could check for each and every one of these things:
调用该函数collections.namedtuple
会为您提供一个新类型,它是tuple
(没有其他类)的子类,其成员名为_fields
元组,其项目都是字符串。因此,您可以检查以下每一件事:
def isnamedtupleinstance(x):
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return all(type(n)==str for n in f)
it IS possible to get a false positive from this, but only if somebody's going out of their way to make a type that looks a lotlike a named tuple but isn't one;-).
有可能得到这样的假阳性,但只有当某人的去他们的出路,使一个类型,看起来很多像一个名为元组,但不是一个;-)。
回答by MatrixManAtYrService
If you want to determine whether an object is an instance of a specific namedtuple, you can do this:
如果要确定对象是否是特定命名元组的实例,可以执行以下操作:
from collections import namedtuple
SomeThing = namedtuple('SomeThing', 'prop another_prop')
SomeOtherThing = namedtuple('SomeOtherThing', 'prop still_another_prop')
a = SomeThing(1, 2)
isinstance(a, SomeThing) # True
isinstance(a, SomeOtherThing) # False
回答by jvdillon
Improving on what Lutz posted:
改进 Lutz 发布的内容:
def isinstance_namedtuple(x):
return (isinstance(x, tuple) and
isinstance(getattr(x, '__dict__', None), collections.Mapping) and
getattr(x, '_fields', None) is not None)
回答by Tor Valamo
If you need to check before calling namedtuple specific functions on it, then just call them and catch the exception instead. That's the preferred way to do it in python.
如果您需要在调用 namedtuple 特定函数之前进行检查,那么只需调用它们并捕获异常即可。这是在 python 中执行此操作的首选方法。
回答by Lutz Prechelt
I use
我用
isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
which to me appears to best reflect the dictionary aspect of the nature of named tuples. It appears robust against some conceivable future changes too and might also work with many third-party namedtuple-ish classes, if such things happen to exist.
在我看来,这似乎最能反映命名元组性质的字典方面。它似乎对一些可以想象的未来变化也很健壮,并且如果碰巧存在这样的事情,它也可能与许多第三方命名的tuple-ish 类一起使用。