I'm totally new to Python and I know this question was asked many times, but unfortunately it seems that my situation is a bit different... I have created a package (or so I think). The catalog tree is like this:
mydir
lib (__init__.py)
mod1 (__init__.py, mod11.py)
In parenthesis there are files in the catalog. Both __init__.py
files are zero length.
The file mydir/lib/mod1/mod11.py
contains the following:
def mod12():
print "mod12"
Now, I run python
, then import lib
, which works OK, then lib.mod11()
or lib.mod12()
.
Either of the last two gives me the subject error message. Actually dir(lib)
after Step 2 does not display mod11
or mod12
either.
It seems I'm missing something really simple.
(I'm using Python 2.6 in Ubuntu 10.10)
Thank you
When you
import lib
, you're importing the package. The only file to get evaluated and run in this case is the 0 byte__init__.py
in the lib directory.If you want access to your function, you can do something like this
from lib.mod1 import mod1
and then run themod12
function like somod1.mod12()
.If you want to be able to access
mod1
when you importlib
, you need to put animport mod1
inside the__init__.py
file inside thelib
directory.My solution is put those imports in
__init__.py
of lib:Then,
would work fine.
The way I would do it is to leave the __ init__.py files empty, and do:
or
You may find that the mod1 dir is unnecessary, just have mod12.py in lib.
More accurately, your
mod1
andlib
directories are not modules, they are packages. The filemod11.py
is a module.Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.
An alternative is to use the
from
syntax to "pull" a module from a package into you scripts namespace.Then reference the function as simply
mod11.mod12()
.