How to split a Python module into multiple files?

Adam picture Adam · Oct 17, 2011 · Viewed 13.6k times · Source

I have a single Python module which contains 3 classes: A, A1 and A2. A1 and A2 derive from A. A contains functions which operate on A1 and A2.

This all works fine when it's in one .py file. But that file has grown quite long and I would like to split A1 and A2 off into their own files. How can I split this file despite a circular dependency?

Answer

spam_eggs picture spam_eggs · Oct 17, 2011

modA.py:

class A(...):
   ...

modA1.py:

import modA
class A1(modA.A):
   ...

modA2.py:

import modA
class A2(modA.A):
   ...

modfull:

from modA import A
from modA1 import A1
from modA2 import A2

Even if A "processes" A1s and A2s you should be fine because thanks to duck typing you don't need to import the actual names.