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

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

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

7条回答
  •  再見小時候
    2020-12-08 19:08

    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.

提交回复
热议问题