Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is an instance of a namedtuple?

How do I check if an object is an instance of a Named tuple?

like image 923
Sridhar Ratnakumar Avatar asked Jan 30 '10 04:01

Sridhar Ratnakumar


People also ask

How do I access Namedtuple elements?

The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

How do you define a Namedtuple?

Python's namedtuple() is a factory function available in collections . It allows you to create tuple subclasses with named fields. You can access the values in a given named tuple using the dot notation and the field names, like in obj. attr .

What is difference between Namedtuple and tuple?

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.

What type is a Namedtuple?

Named tuple container datatype is an alternative to the built-in tuple . This extension type enhances standard tuples so that their elements can be accessed by both their attribute name and the positional index. Named tuples are available in Python's standard library collections module under the namedtuple utility.


2 Answers

Calling the function collections.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:

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 lot like a named tuple but isn't one;-).

like image 148
Alex Martelli Avatar answered Oct 06 '22 09:10

Alex Martelli


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 
like image 24
MatrixManAtYrService Avatar answered Oct 06 '22 08:10

MatrixManAtYrService