3

i noticed some seemingly strange behaviour when trying to import a python module named rmod2 in different ways. if i start python from the directory where the rmod2.py file is located, it works fine. however, if i move the file to another folder where other modules are locate, it doesn't work as expected anymore. the module/package folder is /usr/lib/pymodules/python2.7 and it is also contained in the sys.path. so i've created the folder /usr/lib/pymodules/python2.7/rmod2 and put an empty __init__.py and the rmod2.py in there. if i don't have the __init__.py i get:

>>> import rmod2
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ImportError: No module named rmod2

with the __init__.py file, the import seems to work, but the package is empty:

>>> import rmod2
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'rmod2']
>>> dir(rmod2)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> rmod2.__path__
['/usr/lib/pymodules/python2.7/rmod2']
>>> rmod2.__file__
'/usr/lib/pymodules/python2.7/rmod2/__init__.py'

can someone tell me what's going on, and how to fix it to actually load the module contents when importing?

2 Answers 2

1

You want to add the path to the directory your modules are located in to your sys.path variable instead, or add the rmod.py module directly to a directory on the path (and not in a subdirectory).

By adding __init__.py to a directory, you converted it into a python package instead, making it an importable. If that was your intention, then you moved rmod-the-module inside of a rmod-the-package, and you can import that through that namespace:

from rmod2 import rmod2
Sign up to request clarification or add additional context in comments.

1 Comment

placing the .py file in the top-level module directory seems to have done the trick. thanks.
1

Once it happened to me that a package's modules weren't accesssible from package, but when imported directly, it worked. Probably missing __all__ in package's __init__.py

This didn't work:

import mypkg obj = mypkg.mymodule.MyClass()

This worked:

import mypkg.mymodule
obj = mypkg.mymodule.MyClass()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.