Home > Software design >  Python: Is there a way of knowing whether an instance of a class has been assigned to a variable?
Python: Is there a way of knowing whether an instance of a class has been assigned to a variable?

Time:03-18

I am writing a Body2D class, and under the __add__() magic method I would like to be able to know whether an instance of the class is actually assigned to a variable, or whether it was created just for the addition.

For example, how would I be able to tell the difference between this:

earth = Body2D()
venus = Body2D()
mars = earth   venus

... where both first instances are tied to a variable, and this:

mars = Body2D()   Body2D()

?

The reason I ask is because I have created a class variable (a list) of all the IDs of the objects created so far, and I don't want to store IDs of bodies that have not been assigned to variables.

Any help would be much appreciated! Thanks!

CodePudding user response:

This isn't possible. From the perspective of your class instances, nothing changes at the moment of assignment aside from their reference count failing to be decremented, since the reference count is incremented when they're loaded onto the stack; popping from the stack to store to a variable transfers ownership to the variable, that's all. This isn't C where assignment involves constructor or assignment operators being invoked to execute custom code; in the general case, there is zero instance observable difference between creating an object temporarily and creating it for longer term storage in a named variable.

I suspect an XY problem here, and in all likelihood your true solution will end up using the weakref module in some way to track which objects remain referenced (without holding a reference yourself that would prevent the objects from being cleaned up).

  • Related