How can I split a module into multiple files, without breaking a backwards compatibly?
Question:
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
.
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>
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
.
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>