オブジェクトが名前付きタプルのインスタンスであるかどうかを確認するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/2166818

質問

オブジェクトが のインスタンスであるかどうかを確認するにはどうすればよいですか? 名前付きタプル?

役に立ちましたか?

解決

電話をかける 関数 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)

これにより誤検知が発生する可能性はありますが、それは誰かがわざわざ次のような型を作成した場合に限られます。 多く 名前付きタプルに似ていますが、名前付きタプルではありません;-)。

他のヒント

私はこれが古い実現が、私はこれが有用であることが分かっます:

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

あなたがそれにnamedtupleの特定の関数を呼び出す前にチェックする必要がある場合は、単にそれらを呼び出す代わりに、例外をキャッチ。これは、Pythonでそれを行うための好ましい方法です。

ルッツが掲示ものに改善ます:

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

私が使用して

isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
私には最高に表示されます。という名前のタプルの性質の辞書側面を反映しています。 このようなことが存在するために起こる場合は、あまりにもおよびかもしれない多くのサードパーティnamedtupleっぽいクラスと仕事を変えるいくつか考えられる将来に対して堅牢表示されます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top