1

I have a package with several nested modules:

somepackage/
  module1/
    __init__.py
    module2/
      __init__.py
      to_be_imported.py
setup.py

I have installed this package with python setup.py develop. The to_be_imported.py file contains a few classes and a method (after the classes, since the method uses some classmethods of the classes). After opening an IPython console, the following import works:

from somepackage.module1.module2.to_be_imported import SomeClass

but this one fails with ImportError:

from somepackage.module1.module2.to_be_imported import my_method

Moreover, if I import the file as

from somepackage.module1.module2 import to_be_imported

and print the imported file content, it prints my_method too!

I am confused about what causes the import error, does anybody encountered such problems?

Hodossy Szabolcs
  • 1,598
  • 3
  • 18
  • 34
  • Are you sure you imported `to_be_imported` inside `module2/__init__.py` with: `from .somepackage.module1.module2.to_be_imported import *` – mertyildiran Apr 25 '17 at 09:42
  • Sorry, I had a typo in the question, forget to add .to_be_imported to the first two imports, my __init__.py files are empty – Hodossy Szabolcs Apr 25 '17 at 09:50

2 Answers2

2

Note that module2 is a misnomer, as it isn't actually a module but a subpackage.

You have access to SomeClass because it has been imported from to_be_imported into module2.__init__.py. You can open module2.__init__.py to confirm this.

To access that function, you should specify the full path:

from somepackage.module1.module2.to_be_imported import my_method

Or have it imported into module2.__init__.py to use the shorter path.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

As it turns out, my problem was that my module was cached into my IPython session. I added my_method later, so the cached version did not contain it, but when I printed the file, it printed the newest version. More on the topic: Prevent Python from caching the imported modules

To summarize: a console restart is all I needed.

Community
  • 1
  • 1
Hodossy Szabolcs
  • 1,598
  • 3
  • 18
  • 34