Python 对象是否可以检查变量的名称;谁被派去了?
在Python中,有没有一种方法可以让对象的实例看到分配给它的变量名?以以下为例:Python 对象是否可以检查变量的名称;谁被派去了?,python,Python,在Python中,有没有一种方法可以让对象的实例看到分配给它的变量名?以以下为例: class MyObject(object): pass x = MyObject() MyObject是否可能在任何时候看到它被分配给变量名x?就像它的uu init uu方法一样没有。对象和名称存在于不同的维度中。一个对象在其生命周期内可以有多个名称,并且无法确定哪一个可能是您想要的名称。即使在这里: class Foo(object): def __init__(self): pass
class MyObject(object):
pass
x = MyObject()
MyObject是否可能在任何时候看到它被分配给变量名x?就像它的uu init uu方法一样没有。对象和名称存在于不同的维度中。一个对象在其生命周期内可以有多个名称,并且无法确定哪一个可能是您想要的名称。即使在这里:
class Foo(object):
def __init__(self): pass
x = Foo()
两个名称表示同一个对象(
self
当\uuu init\uuu
运行时,x
在全局范围内)。是的,这是可能的*。然而,这个问题比乍一看要困难得多:
- 同一对象可能有多个名称
- 可能根本没有名字
- 相同的名称可能引用不同命名空间中的其他对象
import gc, inspect
def find_names(obj):
frame = inspect.currentframe()
for frame in iter(lambda: frame.f_back, None):
frame.f_locals
obj_names = []
for referrer in gc.get_referrers(obj):
if isinstance(referrer, dict):
for k, v in referrer.items():
if v is obj:
obj_names.append(k)
return obj_names
<>如果你想把逻辑围绕变量的名字,暂停一下,考虑重新设计/重构代码是否能解决这个问题。从对象本身恢复对象名称的需要通常意味着程序中的底层数据结构需要重新考虑
*至少在Cpython中,这是无法正常完成的,尽管这可以通过使用内省和调试程序的工具来实现。但是,代码必须从“.py”文件运行,而不仅仅是从编译的字节码运行,或者在压缩模块中运行——因为它依赖于从应该找到“运行位置”的方法中读取文件源代码 诀窍是访问初始化对象的执行帧-使用inspect.currentframe-frame对象有一个“f_lineno”值,该值表示调用对象方法(在本例中为
\uuu init\uuu
)的行号。函数inspect.filename允许检索文件的源代码,并获取适当的行号
然后,一个简单的分析会窥视预先给出“=”符号的部分,并假设它是包含该对象的变量
from inspect import currentframe, getfile
class A(object):
def __init__(self):
f = currentframe(1)
filename = getfile(f)
code_line = open(filename).readlines()[f.f_lineno - 1]
assigned_variable = code_line.split("=")[0].strip()
print assigned_variable
my_name = A()
other_name = A()
这不适用于多个赋值、在赋值前与对象组成的表达式、将对象追加到列表或添加到字典或集合、初始化for
循环中的对象实例化,天知道还有哪些情况--
记住,在第一个属性之后,对象也可以被任何其他变量引用
波顿线:这是可能的,但作为玩具-它不能用于生产代码-
只需在对象初始化期间将varibal名称作为字符串传递,就像创建集合时必须做的那样。namedtuple
如果您需要名称,那么“正确的方法”是将名称作为字符串参数显式地传递给对象初始化,如:
class A(object):
def __init__(self, name):
self.name = name
x = A("x")
而且,如果绝对只需要输入一次对象的名称,还有另一种方法——继续阅读。
由于Python的语法,一些特殊的赋值(不使用“=”操作符)确实允许对象知道它被分配了名称。因此,在Python中执行赋值的其他statemtn是for、with、def和class关键字,这可能会被滥用,因为类创建和函数定义都是赋值语句,用于创建“知道”其名称的对象
让我们关注def
语句。它通常创建一个函数。但是使用decorator,您可以使用“def”创建任何类型的对象,并使构造函数可以使用函数的名称:
class MyObject(object):
def __new__(cls, func):
# Calls the superclass constructor and actually instantiates the object:
self = object.__new__(cls)
#retrieve the function name:
self.name = func.func_name
#returns an instance of this class, instead of a decorated function:
return self
def __init__(self, func):
print "My name is ", self.name
#and the catch is that you can't use "=" to create this object, you have to do:
@MyObject
def my_name(): pass
(这最后一种方法可以在生产代码中使用,不同于读取源文件的方法)这里有一个简单的函数来实现您想要的功能,假设您希望从方法调用中检索分配实例的变量名:
import inspect
def get_instance_var_name(method_frame, instance):
parent_frame = method_frame.f_back
matches = {k: v for k,v in parent_frame.f_globals.items() if v is instance}
assert len(matches) < 2
return list(matches.keys())[0] if matches else None
正如许多其他人所说,这是不可能正确完成的。无论受到jsbueno的启发,我都有一个替代方案来替代他的解决方案 与他的解决方案一样,我检查了调用者堆栈框架,这意味着它仅适用于Python实现的调用者(请参见下面的注释)。与他不同,我直接检查调用方的字节码(而不是加载和解析源代码)。使用Python3.4+的
dis.get_instructions()
可以做到这一点,但希望兼容性最小。虽然这仍然是一些黑客代码
import inspect
import dis
def take1(iterator):
try:
return next(iterator)
except StopIteration:
raise Exception("missing bytecode instruction") from None
def take(iterator, count):
for x in range(count):
yield take1(iterator)
def get_assigned_name(frame):
"""Takes a frame and returns a description of the name(s) to which the
currently executing CALL_FUNCTION instruction's value will be assigned.
fn() => None
a = fn() => "a"
a, b = fn() => ("a", "b")
a.a2.a3, b, c* = fn() => ("a.a2.a3", "b", Ellipsis)
"""
iterator = iter(dis.get_instructions(frame.f_code))
for instr in iterator:
if instr.offset == frame.f_lasti:
break
else:
assert False, "bytecode instruction missing"
assert instr.opname.startswith('CALL_')
instr = take1(iterator)
if instr.opname == 'POP_TOP':
raise ValueError("not assigned to variable")
return instr_dispatch(instr, iterator)
def instr_dispatch(instr, iterator):
opname = instr.opname
if (opname == 'STORE_FAST' # (co_varnames)
or opname == 'STORE_GLOBAL' # (co_names)
or opname == 'STORE_NAME' # (co_names)
or opname == 'STORE_DEREF'): # (co_cellvars++co_freevars)
return instr.argval
if opname == 'UNPACK_SEQUENCE':
return tuple(instr_dispatch(instr, iterator)
for instr in take(iterator, instr.arg))
if opname == 'UNPACK_EX':
return (*tuple(instr_dispatch(instr, iterator)
for instr in take(iterator, instr.arg)),
Ellipsis)
# Note: 'STORE_SUBSCR' and 'STORE_ATTR' should not be possible here.
# `lhs = rhs` in Python will evaluate `lhs` after `rhs`.
# Thus `x.attr = rhs` will first evalute `rhs` then load `a` and finally
# `STORE_ATTR` with `attr` as instruction argument. `a` can be any
# complex expression, so full support for understanding what a
# `STORE_ATTR` will target requires decoding the full range of expression-
# related bytecode instructions. Even figuring out which `STORE_ATTR`
# will use our return value requires non-trivial understanding of all
# expression-related bytecode instructions.
# Thus we limit ourselfs to loading a simply variable (of any kind)
# and a arbitary number of LOAD_ATTR calls before the final STORE_ATTR.
# We will represents simply a string like `my_var.loaded.loaded.assigned`
if opname in {'LOAD_CONST', 'LOAD_DEREF', 'LOAD_FAST',
'LOAD_GLOBAL', 'LOAD_NAME'}:
return instr.argval + "." + ".".join(
instr_dispatch_for_load(instr, iterator))
raise NotImplementedError("assignment could not be parsed: "
"instruction {} not understood"
.format(instr))
def instr_dispatch_for_load(instr, iterator):
instr = take1(iterator)
opname = instr.opname
if opname == 'LOAD_ATTR':
yield instr.argval
yield from instr_dispatch_for_load(instr, iterator)
elif opname == 'STORE_ATTR':
yield instr.argval
else:
raise NotImplementedError("assignment could not be parsed: "
"instruction {} not understood"
.format(instr))
注意:C实现的函数不会显示为Python堆栈框架,因此在此脚本中是隐藏的。这将导致误报。考虑Python函数<代码> f>(<代码> >,它调用<代码> A= G.())<代码>。code>g()是C实现的,并调用b=f2()
。当f2()
尝试查找分配的名称时,它将得到a
而不是b
,因为脚本对C函数不敏感。(至少我想这就是它的工作原理:P)
用法示例:
class MyItem():
def __init__(self):
self.name = get_assigned_name(inspect.currentframe().f_back)
abc = MyItem()
assert abc.name == "abc"
假设:
class MyObject(object):
pass
x = MyObject()
然后,您可以通过对象的id在环境中搜索,当存在匹配项时返回密钥
keys = list(globals().keys()) # list all variable names
target = id(x) # find the id of your object
for k in keys:
value_memory_address = id(globals()[k]) # fetch id of every object
if value_memory_address == target:
print(globals()[k], k) # if there is a variable assigned to that id, then it is a variable that points to your object
我正在独立地进行这项工作,并有以下几点。它没有driax的答案那么全面,但有效地涵盖了描述的情况,并且不依赖于在全局变量中搜索对象的id或解析源代码
import sys
import dis
class MyObject:
def __init__(self):
# uses bytecode magic to find the name of the assigned variable
f = sys._getframe(1) # get stack frame of caller (depth=1)
# next op should be STORE_NAME (current op calls the constructor)
opname = dis.opname[f.f_code.co_code[f.f_lasti+2]]
if opname == 'STORE_NAME': # not all objects will be assigned a name
# STORE_NAME argument is the name index
namei = f.f_code.co_code[f.f_lasti+3]
self.name = f.f_code.co_names[namei]
else:
self.name = None
x = MyObject()
x.name == 'x'
简单的回答是:不,不要尝试。。而真正的答案是肯定的,但不要尝试……)令人惊讶,而且非常简洁。顺便说一句,我认为编写一些小的实用程序包,例如在Jupyter笔记本或调试会话中进行交互式使用,对于此类黑客来说是完全合法的。只是不要在生产代码中使用它,它现在已经使用了。使用Python 3.6.2进行测试
import sys
import dis
class MyObject:
def __init__(self):
# uses bytecode magic to find the name of the assigned variable
f = sys._getframe(1) # get stack frame of caller (depth=1)
# next op should be STORE_NAME (current op calls the constructor)
opname = dis.opname[f.f_code.co_code[f.f_lasti+2]]
if opname == 'STORE_NAME': # not all objects will be assigned a name
# STORE_NAME argument is the name index
namei = f.f_code.co_code[f.f_lasti+3]
self.name = f.f_code.co_names[namei]
else:
self.name = None
x = MyObject()
x.name == 'x'