Q: Name of a arbitary variable as a string?
Jeff Epler
jepler at unpythonic.net
Tue Nov 12 19:10:58 EST 2002
On Tue, Nov 12, 2002 at 09:01:28PM +0100, username wrote:
> I am searching for a function (call it: var_name) that do something like
> this:
>
> >>> V="Hello World"
> >>> var_name(V)
> 'V'
Here's a very nasty little piece of work which makes a few assumptions
about the kindly nature of the caller and the structure of Python
bytecodes.
I recommed that you not use this code. You should probably find another
way to do whatever it is you're trying to do. For instance, you could
replace
var_name(V)
with
"V"
BTW, this code is broken at least for LOAD_DEREF and probably for
LOAD_NAME.
# IF YOU USE THIS CODE YOU WILL DIE
def var_name(arg):
f = sys._getframe(1)
c = f.f_code.co_code
ip = f.f_lasti
i = ord(c[ip-3])
o = ord(c[ip-2]) + 256*ord(c[ip-1])
r = []
while dis.opname[i] == 'LOAD_ATTR':
r.append(f.f_code.co_names[o])
ip=ip-3
i = ord(c[ip-3])
o = ord(c[ip-2]) + 256*ord(c[ip-1])
if dis.opname[i] == 'LOAD_FAST':
r.append(f.f_code.co_varnames[o])
r.append(f.f_code.co_names[o])
r.reverse()
print r
return ".".join(r)
More information about the Python-list
mailing list