Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable name introspection in Python

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.)

like image 745
AnC Avatar asked Dec 02 '22 06:12

AnC


2 Answers

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.

like image 96
Alex Martelli Avatar answered Dec 15 '22 00:12

Alex Martelli


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.

like image 42
Alok Singhal Avatar answered Dec 14 '22 23:12

Alok Singhal