[Tutor] my own site-package

Jeff Shannon jeff at ccvcorp.com
Wed Oct 6 19:45:10 CEST 2004


nik wrote:

> If I run the python interpreter in the same folder as my module, then 
> doing;
>
> import mymodule
>
> works fine, and I'm able to call all the methods in mymodule.py
>
> If I create a folder called mymodule under site-packages, then the 
> above doesn't work *unless* I do;
>
> from mymodule import *


Kent already explained how to get things working the way you want them 
to, but I thought it might be worthwhile to explain what's happening 
here in a little more detail.

As Kent said, what you've done is to create a package named 'mymodule'.  
If you have a file module1.py inside of that folder, then normally you'd 
refer to that using package syntax, i.e.:

    import mymodule.module1

This would then allow you to refer to 'mymodule.module1.foo()'.  You 
could also import only specific names from the mymodule package, like so:

    from mymodule import module1

This is the same import, but it binds your module to the name 'module1' 
instead of the name 'mymodule.module1'.  That means that, instead of 
using 'mymodule.module1.foo()', you can just use 'module1.foo()'.

What you've done above, using the wildcard import, does the same thing 
as my second example here for *each* name that would normally appear 
directly in the 'mymodule' package.  That means that any modules that 
are part of the package will be accessible with (what appears to be) an 
unqualified name.  It also means that global names from your __init__.py 
file will be imported into your current namespace.

Generally, using the 'from module_or_package import *' form is not 
recommended, because it does have a tendency to accidentally trample 
names.  If the imported module has a main() function, and your importing 
code has a main() function, you'll only be able to access *one* of those 
functions -- whichever one was defined last.  And if the imported module 
has, say, a open() function, then that function will hide the builtin 
open() file-creation function.

In your case, as Kent said, all you need to do is move your module1.py 
out of the subfolder and put it directly into site-packages.  Then you 
can simply 'import module1' and not worry about having an __init__.py or 
whether you're injecting unnecessary names into your namespace. :)

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list