Import subclass from a base class in Python

Kevin Li picture Kevin Li · Nov 30, 2011 · Viewed 13.6k times · Source

I have a base class that has a method that creates an instance of a subclass that is called the same as the input string.

This worked before by putting the subclasses and the base class in the same file, and doing something like globals()[name].

Now, however, I've split up the subclasses into other files. They each have an import base statement at the top, so I can't just simply import the subclasses in my base class or there'll be a chain of circular importing.

Is there any workaround for this?

In base.py:

from basefactory import BaseFactory
class Base:
    def __init__(self, arg1, arg2):
        ...
    def resolve(self, element):
        className = typing.getClassName(element)
        return BaseFactory.getInstance(className, element, self)

In basefactory.py:

from file1 import *
from file2 import *
...
class BaseFactory:
    @staticmethod
    def getInstance(name, arg1, arg2):
       subclass = globals()[name]
       return subclass(arg1, arg2)

In file1.py:

from base import Base

class subclass1(Base):
    def foo(self):
        return self.arg1

Answer

jcollado picture jcollado · Nov 30, 2011

You can move the import statement that is failing to the method that creates the subclass object.