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?
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
We can use a for loop to iterate through the contents of the data file after opening it with Python's 'with' statement. After reading the data, the split() method is used to split the text into words. The split() method by default separates text using whitespace.
Using multiple files to create sub-modules helps keep the code organized and makes reusing code between projects/functions much easier. Functions and variables defined within a module importable into other modules and allows you to scope your function and variable names without worrying about conflicts.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With