3

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:

IPython works, python does not.

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.

webelo
  • 1,646
  • 1
  • 14
  • 32
  • have you tried to put the entire path??? – Micolho May 24 '18 at 16:11
  • Possible duplicate of [How to import other Python files?](https://stackoverflow.com/questions/2349991/how-to-import-other-python-files) – Micolho May 24 '18 at 16:53
  • @Micolho, he is not just asking how to make it work, he is also asking why it works differently on **iPython** – David May 24 '18 at 17:03

1 Answers1

0

I cannot explain to you why that happens, but maybe it could work on python if you make the b.py file look like this:

from a import foo
foo()

For me, it doesn't make sense to use src.a because src is the (same) directory. But again, I do not know why one works and the other doesn't. Refer to the 3rd example on this answer

David
  • 271
  • 1
  • 15