How can I get the name of an object?

Solution 1:

Objects do not necessarily have names in Python, so you can't get the name.

It's not unusual for objects to have a __name__ attribute in those cases that they do have a name, but this is not a part of standard Python, and most built in types do not have one.

When you create a variable, like the x, y, z above then those names just act as "pointers" or "references" to the objects. The object itself does not know what name you are using for it, and you can not easily (if at all) get the names of all references to that object.

Update: However, functions do have a __name__ (unless they are lambdas) so, in that case you can do:

dict([(t.__name__, t) for t in fun_list])

Solution 2:

That's not really possible, as there could be multiple variables that have the same value, or a value might have no variable, or a value might have the same value as a variable only by chance.

If you really want to do that, you can use

def variable_for_value(value):
    for n,v in globals().items():
        if v == value:
            return n
    return None

However, it would be better if you would iterate over names in the first place:

my_list = ["x", "y", "z"] # x, y, z have been previously defined

for name in my_list:
    print "handling variable ", name
    bla = globals()[name]
    # do something to bla

 

Solution 3:

This one-liner works, for all types of objects, as long as they are in globals() dict, which they should be:

def name_of_global_obj(xx):
    return [objname for objname, oid in globals().items()
            if id(oid)==id(xx)][0]

or, equivalently:

def name_of_global_obj(xx):
    for objname, oid in globals().items():
        if oid is xx:
            return objname

Solution 4:

If you are looking to get the names of functions or lambdas or other function-like objects that are defined in the interpreter, you can use dill.source.getname from dill. It pretty much looks for the __name__ method, but in certain cases it knows other magic for how to find the name... or a name for the object. I don't want to get into an argument about finding the one true name for a python object, whatever that means.

>>> from dill.source import getname
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> squared = lambda x:x**2
>>> 
>>> print getname(add)
'add'
>>> print getname(squared)
'squared'
>>> 
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
... 
>>> f = Foo()
>>> 
>>> print getname(f.bar)
'bar'
>>> 
>>> woohoo = squared
>>> plus = add
>>> getname(woohoo)
'squared'
>>> getname(plus)
'add'

Solution 5:

As others have mentioned, this is a really tricky question. Solutions to this are not "one size fits all", not even remotely. The difficulty (or ease) is really going to depend on your situation.

I have come to this problem on several occasions, but most recently while creating a debugging function. I wanted the function to take some unknown objects as arguments and print their declared names and contents. Getting the contents is easy of course, but the declared name is another story.

What follows is some of what I have come up with.

Return function name

Determining the name of a function is really easy as it has the __name__ attribute containing the function's declared name.

name_of_function = lambda x : x.__name__

def name_of_function(arg):
    try:
        return arg.__name__
    except AttributeError:
        pass`

Just as an example, if you create the function def test_function(): pass, then copy_function = test_function, then name_of_function(copy_function), it will return test_function.

Return first matching object name

  1. Check whether the object has a __name__ attribute and return it if so (declared functions only). Note that you may remove this test as the name will still be in globals().

  2. Compare the value of arg with the values of items in globals() and return the name of the first match. Note that I am filtering out names starting with '_'.

The result will consist of the name of the first matching object otherwise None.

def name_of_object(arg):
    # check __name__ attribute (functions)
    try:
        return arg.__name__
    except AttributeError:
        pass

    for name, value in globals().items():
        if value is arg and not name.startswith('_'):
            return name

Return all matching object names

  • Compare the value of arg with the values of items in globals() and store names in a list. Note that I am filtering out names starting with '_'.

The result will consist of a list (for multiple matches), a string (for a single match), otherwise None. Of course you should adjust this behavior as needed.

def names_of_object(arg):
    results = [n for n, v in globals().items() if v is arg and not n.startswith('_')]
    return results[0] if len(results) is 1 else results if results else None