getting the name of a variable

Michael Hudson mwh at python.net
Fri Dec 7 05:17:03 EST 2001


James_Althoff at i2.com writes:

> It seems though, for the narrow purpose requested here, if you are willing
> to turn things around and pass the *name* of the variable instead of its
> value then -- using nested scopes -- one could write something like:

Which nested scopes?  Scopes only nest lexically in Python...

> >>> def prvar(x):
> ...   print x, ':', eval(x)
> ...
> >>> z = 1
> >>> prvar('z')
> z : 1
> >>>
> 
> Might save a little bit of typing.
> 
> >>> def prvar(*varnames):
> ...   for name in varnames:
> ...     print name, ':', eval(name), ';',
> ...
> >>> a = 1
> >>> b = 2
> >>> c = 3
> >>> prvar('a','b','c')
> a : 1 ; b : 2 ; c : 3 ;

This will only work if you call prvar in the scope which defines it,
which is probably a bit too inflexible...

Cheers,
M.

-- 
  I'll write on my monitor fifty times 'I must not post self-indulgent
  wibble nobody is interested in to ucam.chat just because I'm bored
  and I can't find the bug I'm supposed to fix'.
                                            -- Steve Kitson, ucam.chat



More information about the Python-list mailing list