Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
Adam Avatar asked Oct 17 '11 20:10

Adam


People also ask

How do you split a Python script?

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.

How do I split a text file into multiple files in Python?

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.

Does Python support multiple files?

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.


Video Answer


2 Answers

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.

like image 70
spam_eggs Avatar answered Sep 21 '22 01:09

spam_eggs


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.

like image 41
SingleNegationElimination Avatar answered Sep 23 '22 01:09

SingleNegationElimination