Here's my problem. I fire up a fresh python console and I type in the following:
import gc
meeseeks_instance = False
class Meeseeks(object):
def __init__(self):
gc.collect()
print('Look at me!')
def __del__(self):
print('Mission accomplished!')
globals()['meeseks_instance'] = False
def __new__(cls):
gc.collect()
if globals()['meeseeks_instance']:
raise Exception('Theres already a Meeseeks!')
globals()['meeseeks_instance'] = True
return super().__new__(cls)
Now, if I type:
>>> mymeeseeks = Meeseeks()
Look at me!
>>> del mymeeseeks
Mission accomplished!
Fantastic. Now:
>>> Meeseeks()
Look at me!
<Meeseeks object at 0x043DE290>
The object was not assigned, so it's not reachable and it should be garbag collected; anyways, it seems that garbage collection was not yet run. But, if I force it, the object is correctly collected:
>>> gc.collect()
Mission accomplished!
0
And here starts the trouble. If I try to instantiate two Meeseeks
, the explicit garbage collection in __new__
does not fire and the Exception is raised:
>>> Meeseeks()
Look at me!
<Meeseeks object at 0x043B0990>
>>> Meeseeks()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 18, in __new__
Exception: Theres already a Meeseeks!
Why does this happen? How can I make so that trying to instantiate a new Meeseeks forces garbage collection of the previous, unreachable Meeseeks?