'Python submodule imports using __init__.py
I'm learning Python, and I can't figure out how imports in __init__.py work.
I understand from the Python tutorial that the __init__.py file initializes a package, and that I can import subpackages here.
I'm doing something wrong, though. Could you explain for me (and for future Python-learners) what I'm doing wrong?
Here's a simplified example of what I'm trying to do.
This is my file structure:
package
__init__.py
test.py
subpackage
__init__.py
hello_world.py
The contents of hello_world.py:
def do_something():
print "Hello, world!"
subpackage/__init__.py is empty.
package/__init__.py contains:
import test.submodule.do_something
And finally, test.py contains:
do_something()
This is how I attempt to run hello_world.py using OSX terminal and Python 3:
python test.py
Python then throws the following error:
NameError: name 'do_something' is not defined
Solution 1:[1]
First, you have to understand how import alone work:
import test.submodule.do_something
Would try to load do_something from submodule itself loaded from test.
You want to load something from subpackage, so start with that:
import subpackage
Fine, subpackage/__init__.py is loaded.
Now, you want the do_something() function which is in the file (a "module") hello_world.py. Easy:
from subpackage.hello_world import do_something
And you are done! Just read this line loud, it does exactly what it says: import do_something from the module hello_world which is in the subpackage package.
Try that in test.py
from subpackage.hello_world import do_something
do_something()
It should work just fine.
Now, the second issue:
__init__.py won't be called in package/ since you don't use package/ as a package. __init__.py will be used if you do an import of package/ or anything in it, for eg:
from package import test
Otherwise, it won't be loaded at all.
However, if you want to load do_something() on the import of subpackage, put from submodule.hello_word import do_something in subpackage/__init__.py, and then, in you test.py, do a import subpackage.
Solution 2:[2]
It's an absolute hard-and-fast rule in Python that a name must always be defined or imported within the module where you're using it. Here you never import anything inside test.py - so as the error says, do_something is not defined.
Even if your package/__init__.py file was executed (which, as others have pointed out, it isn't), your code still wouldn't work as it is, because the import of do_something has to be done inside test.py if you want to reference it in that file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Daniel Roseman |
