How do I check the name of a namedtuple?

Question:

I have a list of namedtuples, for example:

[Student(ID='1', name='abc'), Room(number='1', location='4th floor'), Student(ID='2', name='xyz')]

While looping through this list, how do I check if an element is a Student or Room?

Asked By: Neeraja

||

Answers:

You can use isinstance to check an object is an instance of a class.

>>> help(isinstance)
Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.

    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.

>>>
>>> from collections import namedtuple
>>>
>>> Student = namedtuple('Student', ['ID', 'name'])
>>> Room = namedtuple('Room', ['location', 'floor'])
>>>
>>> obj = Student(ID=1, name='user')
>>> isinstance(obj, Student)
True
>>> isinstance(obj, Room)
False

If you are looking for class name you can get it by accessing obj.__class__.__name__

>>> obj = Student(ID=1, name='user')
>>> obj.__class__.__name__
'Student'
Answered By: Abdul Niyas P M
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.