0

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?

2
  • Do You mean from subbar import module1? (Be careful mind a cyclic import) Commented Jun 14, 2013 at 8:32
  • oleg, I change my question, thank you Commented Jun 14, 2013 at 8:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

works for me... tested with your updated version gist.github.com/rxdazn/5780497 (just updated gist a few seconds ago, reload it)
Yes. if I use from bar import module1, it works. But, if I use import bar.module1, it does not work
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()
Oh, I see. Is there any method to do it except adding code in __init__.py file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.