I’m building my own lightweight orm. I’d like to keep instantiated objects in a class variable (perhaps a dictionary). When I request an object (through a class method) like get(id), I’d like to return the object from the instantiated list, or create one if it does not exist.
Is there a way to prevent the instantiation of an object (if its id already exists in the cls list)?
There are two straightforward ways of doing it – and many other ways,as well. One of them, as you suggest, is to write the
__new__method for your objects, which could return an already existing object or create a new instance.Another way is to use a factory function for your objects – and call this factory function instead of the class – more or less like this: