I'm trying to implement a factory function that creates subclasses of a given base class (comparing to a string of its name for now). I have this
class Base(object):
...
And in another file I have
class Sub(Base):
...
I'm keeping those classes separated into files because I'm going to have many sub classes and I don't want to define them all in one large file (I would settle for just forward-declaring if possible somehow).
Now in the "Base" file, I want to implement a function to create an instance out of a given name, but Base.__subclasses__()
is None, so I can't do something like this:
def factory(name):
for Subclass in Base.__subclasses__()
if name is ...
return Subclass()
My question is what is the best approach to implement this kind of pattern. In the future I'd like to change this to maybe use a hashtable, but I can't get this simple "string based" example to work.