Skip to content
Advertisement

How can I get the name of an object?

Suppose I have code like:

x = 0
y = 1
z = 2

my_list = [x, y, z]

for item in my_list:
    print("handling object ", name(item)) # <--- what would go instead of `name`?

How can I get the name of each object in Python? That is to say: what could I write instead of name in this code, so that the loop will show handling object x and then handling object y and handling object z?


In my actual code, I have a dict of functions that I will call later after looking them up with user input:

def fun1():
    pass
def fun2():
    pass
def fun3():
    pass

fun_dict = {'fun1': fun1,
            'fun2': fun2,
            'fun3': fun3}

# suppose that we get the name 'fun3' from the user
fun_dict['fun3']()

How can I create fun_dict automatically, without writing the names of the functions twice? I would like to be able to write something like

fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises

fun_dict = {}
for t in fun_list:
    fun_dict[name(t)] = t

to avoid duplicating the names.

Advertisement

Answer

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

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(s) you are using for it, and you can not easily (if at all) get the names of all references to that object.

However, it’s not unusual for objects to have a __name__ attribute. Functions do have a __name__ (unless they are lambdas), so we can build fun_dict by doing e.g.

fun_dict = {t.__name__: t for t in fun_list)
Advertisement