names

Alex Martelli aleaxit at yahoo.com
Mon Jan 15 06:24:10 EST 2001


"Andrew H. Chatham" <andrew.spambgone.chatham at duke.edu> wrote in message
news:slrn964p3g.2f5.andrew.spambgone.chatham at fizgig.dorm.duke.edu...
> On Mon, 15 Jan 2001 01:26:45 GMT, Elliott Chapin <echapin at sympatico.ca>
wrote:
> >How can I get the name of an object as a string? As a biginner I might
> >imagine something like
> >
> >>>>b=[[1],[2]]
> >>>>name(b)
> >'b'
>
> You can't. The object doesn't know what it's name is, because the name
> corresponds to the reference to the object, not the actual object. It's
> sometimes tough to realize that variables don't store objects, they store
> references to objects.

Right!  The only way I see to accomplish Elliott's request is to look
through all variables and return the set of those whose references
are identical to the one being asked for.  To do that in a function,
while looking through the *caller*'s namespace, requires accessing
the stack, which is done by raising and catching an exception; once
that is done, the f_locals and f_globals attributes of the caller's
frame object provide such access.

All in all, something like:

import sys
def name(value):
   try: raise 'foo'
   except 'foo':
       caller_frame = sys.exc_info()[2].tb_frame.f_back
   names = []
   caller_locals = caller_frame.f_locals
   for vname, vval in caller_locals.items():
       if vval is value: names.append(vname)
   for vname, vval in caller_frame.f_globals.items():
       if vval is value and not caller_locals.has_key(vname):
           names.append(vname)
   return names

The name is somewhat misleading, since this function will not return
a string -- rather, a list of strings which are variable names (directly
accessible to the function's caller) naming the given value (it tries
to check for _identity_ of value, with 'is', rather than _equality_
as '==' would do; this is not fully reliable for immutable values, as
it's up to the system whether to have the same identities for equal
objects in that case).  It tries to take into account the scoping effect:
it will not return a global variable name which, from the point of view
of the caller, is 'shadowed' by a local-variable homonym.

> >>>b = [[1],[2]]
> >>>c = b
>
> c and b refer to the same list. If I then tried to hypothetical "name"
> function, the list would have no idea whether to say 'c' or 'b'.

Which is why my non-hypothetical proposed version, above, returns a
list with both names:-).


It's hard to see what such a 'name' function would be good for; maybe
a quick-and-dirty detector for multiply-referenced values in interactive
experimental development (one would then only care about mutable values,
so the indeterminacy affecting immutable ones would not matter).  In
point of fact, I think it's worth little except as a nice show-off for
Python's abilities of introspection/reflection...:-).


Alex






More information about the Python-list mailing list