I've found that IPython and python handle the loading of local modules differently and I wonder if someone could explain why this happens.
Suppose that my project is structured as:
top_level/
src/
a.py
b.py
__init__.py
The contents of b.py
are:
from src.a import foo
foo()
and then a.py
has a function foo
:
def foo():
print('It worked!')
File __init__.py
is blank.
If I call ipython and python from top_level
I get two different result:
Why does one work and not the other? Is it possible to make python handle similar to IPython or is there a more pythonic way to handle cases like this?
Version Info:
- Python: 3.6.3
- IPython: 6.1.0 (with 3.6.3 Python)
Edit to explain difference with "How do I import a local module?" This question is about differences between how IPython and Python handle local module imports, not how to import a local module.
I should also add that - while it is true that my example would work if I changed the import statement to from a import foo
- I was (implicitly) trying to avoid doing this. I like the idea of importing everything relative to some top-level directory in order to make it easier if the structure of the files change. For example, if b.py
was moved from src
to some sub-directory src/core
then you'd need to go through and rewrite all of the imports relative to the new location of b.py
.