display the name of whatever object in python

To display the name of an object in Python, you can use the __name__ attribute. Here's an example:

main.py
class MyClass:
    pass

obj = MyClass()

print(obj.__class__.__name__) # Output: MyClass
90 chars
7 lines

In this example, we create a class MyClass and create an instance of it called obj. We then print the name of the class using the __name__ attribute accessed through the obj.__class__ object.

Alternatively, if you want the name of the object itself, rather than its class, you can use the vars() function to retrieve the object's variables and their values, and then search for the variable that points to the object. Here's an example:

main.py
my_var = MyClass()
var_name = [k for k,v in locals().items() if v is my_var][0]

print(var_name) # Output: my_var
114 chars
5 lines

In this example, we create an instance of MyClass called my_var, and then use the locals() function to get a dictionary of local variables and their values. We then search through this dictionary for the variable that points to my_var by checking if its value is the same as my_var, and finally print the variable name using list comprehension.

gistlibby LogSnag