How can my code discover the name of an object in Python?


No, there’s no way to discover the name of an object in Python. The reason is that the objects don’t really have names.

Let’s say we have the following code. Herein, we cannot find the actual instance name. Since both ob1 and ob2 are bound to the same value, we cannot come to a conclusion that whether the instance name of ob1 or ob2 −

Example

# Creating a Demo Class class Demo: pass Example = Demo ob1 = Example() ob2 = ob1 print(ob2) print(ob1)

Output

<__main__.Demo object at 0x00000250BA6C5390>
<__main__.Demo object at 0x00000250BA6C5390>

As we saw above, we cannot display the exact name of an object. However, we can display the instances and the count as shown in the below examples.

Get the instances of a class

In this example, we have created a Demo class with four instances −

ob1 = Demo()
ob2 = Demo()
ob3 = Demo()
ob4 = Demo()

We loop through the objects in memory −

for ob in gc.get_objects():

Example

Using the isinstance(), each object is checked for an instance of the class Demo. Let us see the complete example −

import gc # Create a Class class Demo: pass # Four objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Display all instances of a given class for ob in gc.get_objects(): if isinstance(ob, Demo): print(ob)

Output

<__main__.Demo object at 0x7f18e74fe4c0>
<__main__.Demo object at 0x7f18e7409d90>
<__main__.Demo object at 0x7f18e7463370>
<__main__.Demo object at 0x7f18e7463400>

Display the count of instances of a class

In this example, we will count the instances and display −

Example

import gc # Create a Class class Demo(object): pass # Creating 4 objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Calculating and displaying the count of instances res = sum(1 for k in gc.get_referrers(Demo) if k.__class__ is Demo) print("Count the instances = ",res)

Output

Count the instances = 4

Updated on: 16-Sep-2022

942 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements