Adam
Adam

Reputation: 17329

How to split a Python module into multiple files?

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?

Upvotes: 18

Views: 15041

Answers (3)

spam_eggs
spam_eggs

Reputation: 1068

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.

Upvotes: 12

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

How can I split this file with despite a circular dependency?

Option 1: break the cycles: Put the base class in its own module, the derived classes in additional modules, and functions operating on those derived classes in yet another module.


Option 2: Ignore the cycles, import only modules/packages into the global namespace, IE:

foo.py

class Bar:
    "Frobs Quuxen"

Should never be imported as from foo import Bar, just use import foo and refer to foo.Bar in functions as needed.

Upvotes: 2

Nick ODell
Nick ODell

Reputation: 25219

I think the core of your question is that you don't want

a.py to imports a1
if
a1.py imports a.

However, that's totally fine in python. However, do make sure that you don't have any code outside of functions/classes in a system with multiple modules, because the order that that runs in will vary based on where you import it, what that imports, the phase of the moon, etc.

Upvotes: 0

Related Questions