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

Sridhar Ratnakumar picture Sridhar Ratnakumar · Jan 30, 2010 · Viewed 17.7k times · Source

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

Answer

Alex Martelli picture Alex Martelli · Jan 30, 2010

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;-).