stevenhaはこの質問に対する素晴らしい答えを持っています。ただし、とにかく名前空間ディクショナリを実際に調べたい場合は、次のように特定のスコープ/名前空間で特定の値のすべての名前を取得できます。
def foo1():
x = 5
y = 4
z = x
print names_of1(x, locals())
def names_of1(var, callers_namespace):
return [name for (name, value) in callers_namespace.iteritems() if var is value]
foo1() # prints ['x', 'z']
スタックフレームをサポートしているPythonを使用している場合(ほとんどの場合、CPythonはサポートしています)、ローカルのdictをnames_of
関数に渡す必要はありません。関数は、呼び出し元のフレーム自体からその辞書を取得できます。
def foo2():
xx = object()
yy = object()
zz = xx
print names_of2(xx)
def names_of2(var):
import inspect
callers_namespace = inspect.currentframe().f_back.f_locals
return [name for (name, value) in callers_namespace.iteritems() if var is value]
foo2() # ['xx', 'zz']
名前属性を割り当てることができる値型を使用している場合は、それに名前を付けてから、次のように使用できます。
class SomeClass(object):
pass
obj = SomeClass()
obj.name = 'obj'
class NamedInt(int):
__slots__ = ['name']
x = NamedInt(321)
x.name = 'x'
最後に、クラス属性を操作していて、それらの名前を知ってもらいたい場合(記述子は明らかなユースケースです)、DjangoORMおよびSQLAlchemy宣言型テーブル定義で行うようにメタクラスプログラミングでクールなトリックを行うことができます。
class AutonamingType(type):
def __init__(cls, name, bases, attrs):
for (attrname, attrvalue) in attrs.iteritems():
if getattr(attrvalue, '__autoname__', False):
attrvalue.name = attrname
super(AutonamingType,cls).__init__(name, bases, attrs)
class NamedDescriptor(object):
__autoname__ = True
name = None
def __get__(self, instance, instance_type):
return self.name
class Foo(object):
__metaclass__ = AutonamingType
bar = NamedDescriptor()
baaz = NamedDescriptor()
lilfoo = Foo()
print lilfoo.bar # prints 'bar'
print lilfoo.baaz # prints 'baaz'