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

后端 未结 7 1548
轮回少年
轮回少年 2020-12-08 18:39

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

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 19:29

    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
    

提交回复
热议问题