Skip to content
Advertisement

How can I get the name of an object?

Suppose I have code like:

JavaScript

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:

JavaScript

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

JavaScript

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.

JavaScript
Advertisement