How to split a Python module into multiple files?

泪湿孤枕 提交于 2019-12-22 01:34:45

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7799286/how-to-split-a-python-module-into-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!