Code: Select all
class MyClass():
pass
def foo():
a = MyClass()
But what if there is no specific reference to the MyClass instance:
Code: Select all
class MyClass():
pass
def foo():
MyClass()
while True:
# Run code
# Might the instance be GC'd here?
Code: Select all
def singleton(cls):
instances = {}
def getinstance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance
Code: Select all
@singleton
class MyClass():
def method(self):
pass
def foo():
MyClass() # Instantiate
while True:
MyClass().method() # Get an instance reference, use it and lose it
# Might the instance be GC'd here?