Let's say I have a model.py
file that looks like this:
class Foo(): .. class Bar(): ..
From other modules I'm importing the model
and then using model.Foo()
whenever I want to refer to them.
import model foo = model.Foo()
As this file is growing bigger I would like to split each class into multiple files, but without breaking the backwards compatibility if possible.
My idea was to break it like this:
model ├── __init__.py ├── foo.py └── bar.py
but by doing that I will have to refer to them as model.foo.Foo()
.
So my question is: is it possible to split it in multiple files somehow but still referring to them as model.Foo()
?
I should also be able to extend or use Foo
inside Bar
.
To split a big binary file in multiple files, you should first read the file by the size of chunk you want to create, then write that chunk to a file, read the next chunk and repeat until you reach the end of original file.
Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
In Python, a module is a single unit of Python code that can be imported (loaded and used) by other Python code. A module can contain definitions (like functions and constants), as well as statements that initialize those definitions.
To make sure Python can always find the module.py , you need to: Place module.py in the folder where the program will execute. Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can place the module.py in one of the folders included in the PYTHONPATH variable.
Sure you can, just import the classes in the __init__.py
:
# in __init__.py from model.foo import Foo from model.bar import Bar
And then when you wish to use them you can:
>>> import model >>> model.Bar() <model.bar.Bar object at 0x31306d0>
or
>>> from model import Foo >>> Foo() <model.foo.Foo object at 0x31307d0>
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