For finally testing modules and subpackages I made a new folder on my Mac OSX Mavericks. Location of the folder is the Desktop:
packtest
|-- importtest.py
|-- thepackage
|-- __init__.py
|-- thesubpackage
|-- __init__.py
|-- mary.py
the mary.py contains a variable:
marie="Hello"
and nothing else.
In the importtest.py I want to print it out. I tried different ways of importing, basically the ones stated in this Python: importing a sub‑package or sub‑module thread.
Also I tried to add __all__ = ["mary"] to the __init__.py in the thesubpackage folder.
But all I tried did not work. Any Ideas?
Edit:
When trying the suggested solutions I got these errors:
import thepackage.thesubpackage.mary
print thepackage.thesubpackage.mary.marie
results in:
$ python importtest.py
Traceback (most recent call last):
File "importtest.py", line 1, in <module>
import thepackage.thesubpackage.mary
ImportError: No module named thepackage.thesubpackage.mary
When trying:
from thepackage.thesubpackage import mary
print mary.marie
The error is:
$ python importtest.py
Traceback (most recent call last):
File "importtest.py", line 1, in <module>
from thepackage.thesubpackage import mary
ImportError: No module named thepackage.thesubpackage
Are 'thepackage', 'thesubpackage', etc. actually the names of the packages you're working with, or have you substituted them here as an example? If the names are different, then you might be suffering from a name collision. Try this, but with the actual name of the package, if it's different:
From within your 'packtest' directory, start a python interpreter, and type:
>>> import thepackage
Did it work? If so, try:
>>> thepackage.__path__
You should see ['thepackage']. If you see something different, that's your problem: you're importing a different package named thepackage, and it probably doesn't have a thesubpackage.mary module, which is where the ImportError is coming from. I'm not sure why this would be the case; Python should be searching in the local directory first, then looking through your PATH and your PYTHONPATH.
EDIT: Here's another possibility: what are the permissions on your 'thepackage' directory and its nested subdirectories? I did an experiment:
$ mkdir something
$ touch something/__init__.py
$ chmod 000 something
$ python
>>> import something
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named something
>>>
$ chmod 744 something
$ python
>>> import something
>>>
To see the permissions, enter ls -l from a terminal within your 'packtest' directory. The first column of output is the permissions.
Having this code in your importtest.py should work:
from thepackage.thesubpackage import mary
print mary.marie
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With