Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python module empty after import

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?

like image 410
tikacp Avatar asked Jan 27 '26 11:01

tikacp


2 Answers

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
like image 160
Martijn Pieters Avatar answered Jan 30 '26 01:01

Martijn Pieters


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()
like image 29
Michel Samia Avatar answered Jan 29 '26 23:01

Michel Samia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!