views:

270

answers:

4

Is it possible to dynamically determine the name of a variable in Python?

For example, I sometimes have the following situation:

name = foo if bar else baz
type = alpha or bravo

D = {
    "name": name,
    "type": type
}

It would be nice if duplication there could be reduced with something like D = makedict(name, type).

Somewhat relatedly, it would sometimes be helpful for a function to know its own name:

class Item(object):

    def item_create(self, item):
        dispatch("create", item)

    def item_delete(self, item):
        dispatch("delete", item)

Here duplication might be reduced by passing something like __methodname__ instead of explicitly repeating "create" and "delete", respectively. (I assume a decorator could be used for this, but that seems like overkill.)

+2  A: 

In general, you can't do this in Python, because Python has objects, not variables.

If I have

L1 = [1,2]
L2 = L1

Then, L1 and L2 both refer to the same object. It has no single name.

Similarly:

def f1(): pass
f2 = f1

Now the function has no single name, and as such, you can't find out "the" name of the function.

An object in Python can be referenced by many names - when the reference count of an object goes to zero, Python frees the memory for it.

Alok
Yeah, I had realized this, but figured there might be some way to figure it out nevertheless. Thanks!
AnC
+7  A: 

In the general case, you cannot deduce the name from a value (there might be no name, there might be multiple ones, etc); when you call your hypothetical makedict(name), the value of name is what makedict receives, so (again, in the general case) it cannot discern what name (if any) the value came from. You could introspect your caller's namespaces to see if you're lucky enough to hit a special case where the value does let you infer the name (e.g., you receive 23, and there's only one name throughout the namespaces of interest which happens to have a value of 23!), but that's clearly a fragile and iffy architecture. Plus, in your first example case, it's absolutely guaranteed that the special case will not occur -- the value in name is exactly the same as in either foo or baz, so it's 100% certain that the name for that value will be hopelessly ambiguous.

You could take a completely different tack, such as calling makedict('name type', locals()) (passing locals() explicitly might be obviated with dark and deep introspection magic, but that's not the most solid choice in general) -- pass in the names (and namespaces, I suggest!) and have makedict deduce the values, which is obviously a much more solid proposition (since each name has exactly one value, but not viceversa). I.e.:

def makedict(names, *namespaces):
  d = {}
  for n in names.split():
    for ns in namespaces:
      if n in ns:
        d[n] = ns[n]
        break
    else:
      d[n] = None  # or, raise an exception

If you're keen on digging out the namespaces by introspection, rather than have them cleanly specified by the caller, look at inspect.getouterframes -- but I suggest you reconsider.

The second issue you raise is quite different (though you could use inspect functions again to introspect the caller's name, or a function's own name -- what a peculiar idea!). What's in common in the two cases is that you're using extremely powerful and dangerous machinery to do a job that could be done much more simply (easier to ensure correctness, easier to debug any problems, easier to test, etc, etc) -- far from having decorators be "overkill", they're far simpler and more explicit than the introspection you propose. If you have a zillion methods all of the form:

def item_blah(self, item):
    dispatch("blah", item)

the simplest way to create them might be:

class Item(object): pass

def _makedispcall(n):
  def item_whatever(self, item):
    dispatch(n, item)
  item_whatever.__name__ = 'item_' + n
  return item_whatever

for n in 'create delete blah but wait theres more'.split():
  setattr(Item, 'item_' + n, _makedispcall(n))

Avoiding repetition is an excellent idea, but runtime introspection is not generally the best way to implement that idea, and Python offers many alternative ways to such implementation.

Alex Martelli
Thanks, this is very insightful. I expected that there'd be no simple solution, and ultimately agree that it's no worth the trouble.
AnC
+1  A: 

You can do what you want for functions:

>>> def blagnorf():
    pass

>>> print blagnorf.__name__
blagnorf

But not for variables, unfortunately. You could probably write a preprocessor for your python code to do it for you, though...

Note that you can do this in Scheme/Lisp with the macro system they have there.

Claudiu
This only works outside the respective function though. Thanks anyway.
AnC
You can get the stack trace and get a reference to the current function being executed that way, from inside the function. or you can also do "blagnorf.__name__" inside the function.
Claudiu
+1  A: 

Whenever you get a hankering to make a gazillion simple methods whose internals only differ according to the method's name, you probably should reconsider your interface. Instead, you could do this:

class Item(object):
    def item_action(self, action, item):
        dispatch(action, item)

where action could be "create", "delete", etc.

unutbu
I agree - unfortunately, I'm not in control of the interface here.
AnC