代码之家  ›  专栏  ›  技术社区  ›  Sridhar Ratnakumar

如何检查对象是否是namedtuple的实例?

  •  26
  • Sridhar Ratnakumar  · 技术社区  · 16 年前

    Named tuple ?

    5 回复  |  直到 7 年前
        1
  •  50
  •   mac    11 年前

    功能 collections.namedtuple 为您提供了一个新类型,它是 tuple _fields 这是一个元组,其项都是字符串。因此,您可以检查以下各项:

    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)
    

    许多 类似于命名元组,但不是一;-)。

        2
  •  30
  •   MatrixManAtYrService    6 年前

    如果要确定对象是否是特定namedtuple的实例,可以执行以下操作:

    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
    
        3
  •  4
  •   Tor Valamo    16 年前

    如果在调用namedtuple特定函数之前需要进行检查,那么只需调用它们并捕获异常即可。这是在python中执行此操作的首选方法。

        4
  •  4
  •   jvdillon    8 年前

    改进Lutz发布的内容:

    def isinstance_namedtuple(x):                                                               
      return (isinstance(x, tuple) and                                                  
              isinstance(getattr(x, '__dict__', None), collections.Mapping) and         
              getattr(x, '_fields', None) is not None)                                  
    
        5
  •  3
  •   techkuz    6 年前

    def isinstance_namedtuple(obj) -> bool:
        return (
                isinstance(obj, tuple) and
                hasattr(obj, '_asdict') and
                hasattr(obj, '_fields')
        )
    
    
        6
  •  1
  •   Lutz Prechelt    12 年前

    我用

    isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
    

    在我看来,这最能反映命名元组本质的字典方面。

        7
  •  0
  •   bformet    6 年前

    在国际海事组织,这可能是最好的解决方案 后来。

    您可以设置一个自定义设置 __module__ 当您实例化namedtuple并稍后检查它时

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

    __模块__

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

    推荐文章