I have created a class that I"m attempting to implement a Singleton pattern on. When __new__ for the class is fired off, I check to see if a class-wide list of instances has a length > 0 or not, and only return the class instance if it's 0 (i.e there isn't already an instance). I've gotten this to MOSTLY work, and can validate that it isn't intstaniating additional objects - however, the reference still exists, even though it returns None. I'm not sure if there is a way to avoid this, as ideally I don't want an empty reference if the instance isn't returned.
The code:
class Dog(Mammal):
_instances = []
_type: str
def __new__(cls,type):
if len(cls._instances) == 0:
instance = super().__new__(cls)
print("no classes yet")
return instance
else:
return
def __init__(self,type):
self._type = type
print("creating a new {} dog".format(self._type))
Dog._instances.append(self)
def sleep(self):
return "Zzzzz...."
@classmethod
def totalDogs(cls):
return len(cls._instances)
# Returns a viable Dog object
fido = Dog("Yorkie")
print(fido.sleep())
rey = Dog("Matlese")
# Returns None, but doesn't throw an error since the reference (rey) still exists:
print(rey)
# Validates that there is only 1 instance
print(fido.totalDogs())
While it's clear an instance hasn't been created and assigned to 'rey', the reference is still valid, although returns None. Is there any way to avoid this? Do I need to raise an Error of some type? Or simply rely on garbage collection?
returnwith no argument is equivalent toreturn None. So what are you expecting it to assign torey?reyyou'll get an error, since it doesn't actually contain a Dog instance.