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

PythonIntrospectionNamedtupleIsinstance

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

3.7+

def isinstance_namedtuple(obj) -> bool:
    return (
            isinstance(obj, tuple) and
            hasattr(obj, '_asdict') and
            hasattr(obj, '_fields')
    )

Solution 4 - Python

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.

Solution 5 - Python

Improving on what Lutz posted:

def isinstance_namedtuple(x):                                                               
  return (isinstance(x, tuple) and                                                  
          isinstance(getattr(x, '__dict__', None), collections.Mapping) and         
          getattr(x, '_fields', None) is not None)                                  

Solution 6 - Python

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.

Solution 7 - Python

IMO this might be the best solution for Python 3.6 and later.

You can set a custom __module__ when you instantiate your namedtuple, and check for it later

from collections import namedtuple

# module parameter added in python 3.6
namespace = namedtuple("namespace", "foo bar", module=__name__ + ".namespace")

then check for __module__

if getattr(x, "__module__", None) == "xxxx.namespace":

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSridhar RatnakumarView Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonMatrixManAtYrServiceView Answer on Stackoverflow
Solution 3 - PythontechkuzView Answer on Stackoverflow
Solution 4 - PythonTor ValamoView Answer on Stackoverflow
Solution 5 - PythonjvdillonView Answer on Stackoverflow
Solution 6 - PythonLutz PrecheltView Answer on Stackoverflow
Solution 7 - PythonbformetView Answer on Stackoverflow