Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a module into multiple files, without breaking a backwards compatibly?

Tags:

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.

like image 690
Lipis Avatar asked Jun 07 '14 18:06

Lipis


People also ask

How do you split a file into parts in Python?

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.

Can modules import other modules?

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).

Can modules import each other Python?

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.

How do I set the path for a Python module?

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.


1 Answers

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> 
like image 149
msvalkon Avatar answered Nov 03 '22 04:11

msvalkon