Note: This is Python 3.5
Given some project thing
such that:
thing/
top.py (imports bar)
utils/
__init__.py (empty)
bar.py (imports foo; has some functions and variables)
foo.py (has some functions and variables)
I can import utils.bar
in top.py, and when running top.py the file bar.py must contain import utils.foo
to get to foo.py's code.
To run bar.py directly though, bar.py must have import foo
instead (import utils.foo
fails). If I make that change then top.py no longer works.
How can I run top.py or bar.py and still use the same import construct in bar.py for both use cases? I feel like I'm missing some simple step or construct, but perhaps expecting bar.py to work independently in this way is asking too much (short of conditional imports or such).
Edit: I've accepted the proper answer, but if you still insist on doing this with some contortions, the following worked for me:
In bar.py
try:
import foo
except ImportError as err:
from . import foo
Then you can run bar.py directly (in my case, as I develop bar.py I'm using some experimental code in an if __main__
block at the bottom of the file). Once my code is well-integrated I remove the conditional and the main part (since it's not meant to run standalone).