1

My directory structure:

test.py
module/
    importer.py
    importee.py
    __init__.py

So in my directory, I have test.py, then another directory which has been initialized as a module. Within that module, there is a file importer.py which imports a file importee.py. In order to test whether the import works, I made a simple function in importee.py and tried using it in importer.py (i.e. I ran importer.py directly); it worked just fine.

But when I go into test.py and have the import statement from module import * and try to run that (without any other code), it gives an error which traces back to the import statement in importer.py, saying No module named 'importee'

If it matters, the __init__.py in the module directory has the __all__ function specified properly.

I like to think this isn't a duplicate despite there being similarly titled posts, such as this or this or this or this; I've been searching for hours and still have no idea what could be causing this.

Any ideas? Any help is greatly appreciated.

Edit: content of the four files:

init.py

__ all __ = ["importee", "importer"]

importee.py

def example():
    print("hey")

importer.py

from importee import * 
example()

test.py

from module import * 

When I run importer.py I get no errors, but when I run test.py I get a error which traces back to the first line of importer.py saying that No module named 'importee' found, even though I don't get that error when running importer.py directly...

James Ronald
  • 685
  • 1
  • 6
  • 13

1 Answers1

0

The following runs and prints "hey" regardless of if you run python test.py from root or python importer.py from module.

You can learn more about relative imports from PEP 328. You can learn more about init here, but the important thing I want you to take away from this is that __init__ runs when you import from module.

Furthermore defining __all__ overrides identifiers that begin with _, and since you aren't using them I don't actually know that it would have any effect.

# test.py
from module import *

# module/__init__.py
from .importer import * 

# module/importee.py
def example():
    print("hey")

# module/importer.py
from .importee import *

example()
Charles Landau
  • 4,187
  • 1
  • 8
  • 24
  • Thank you for the response. I'm having a bit of trouble understanding. Are you suggesting that I have import statements to every file in my module within my `__init__.py`? Would that do anything? Also, the problem was not that I was unable to import the module into test.py, it was that when I imported it for some reason one of the imports used in importer.py (which is *within the module itself*) doesn't work (even though that import works just fine if I run importer.py directly). – James Ronald Jan 21 '19 at 02:28
  • I edited my answer @JamesRonald to hopefully address your question better. You did a good job clarifying – Charles Landau Jan 21 '19 at 06:34