I have a project like that :
foo/
| main.py
| bar/
| | __init__.py
| | module1.py
| | module2.py
And I import module1.py in main.py by import bar.module1.
But I need rewrite bar's function and keep old code. So I change project like that:
foo/
| main.py
| bar/
| | __init__.py
| | oldbar/
| | | module1.py
| | | module2.py
| | | __init__.py
| | newbar/
| | | module1.py
| | | module2.py
| | | __init__.py
Now, I do not want to change main.py, and I still use import bar.module1 in main.py.
Can I do it? add some code into bar/__init__.py?
1 Answer 1
In foo/bar/__init__.py you can write:
from subbar import module1
from subbar import module2
this should allow you to use import bar.module1 from main.py
answered Jun 14, 2013 at 8:45
rxdazn
1,4001 gold badge14 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
rxdazn
works for me... tested with your updated version gist.github.com/rxdazn/5780497 (just updated gist a few seconds ago, reload it)
wenz
Yes. if I use
from bar import module1, it works. But, if I use import bar.module1, it does not workrxdazn
importing will execute
__init__.py files in sub folders (see [docs.python.org/3/reference/… - The import system: regular packages). This means bar/__ini__.py will be executed once bar is imported. By using import bar.module1, bar/__init__.py is not loaded so it does not know bar/newbar/module1 exists. Either use from bar import module1 with module1.hello() or import bar with bar.module1.hello()wenz
Oh, I see. Is there any method to do it except adding code in
__init__.py file?lang-py
from subbar import module1? (Be careful mind a cyclic import)