__import__() with packages

John Roth newsgroups at jhrothjr.com
Sun Apr 4 12:07:31 EDT 2004


"Marco Herrn" <herrn at gmx.net> wrote in message
news:c4p3f2$2j1tnb$1 at ID-165840.news.uni-berlin.de...
> Hi,
>
> I am using the builtin __import__() to import modules. That works for
> simple modules like in this example:
>
>     m= __import__("eggs")
>
> when there is the module "eggs.py" in the current directory
>
> But how do I do this with packages? A I understand the documentation for
> __import__(), it must be something like:
>
>     m= __import__("eggs", globals(), locals(), ["spam"])
>
> when there is the package "spam" in the current directory, containing
> the module "eggs".
> But that doesn't work. I tried it in some different forms. The only one
> that works in some way is:
>
>    m= __import__("spam.eggs")
>
> But that is not what I want, since I get "spam" as a module:
>    <module 'spam' from 'spam/__init__.pyc'>
>
> So what am I doing wrong here?

You're doing everything correctly, just not quite enough.
What you've got is an almost empty module named "spam",
which contains another module bound to the identifier "eggs".

So what you need to do is:

m = __import__("spam.eggs")
eggs = spam.eggs

This will probably also work:

eggs = __import__("spam.eggs").eggs

HTH

John Roth
>
> Marco
>
> -- 
> Marco Herrn             herrn at gmx.net
> (GnuPG/PGP-signed and crypted mail preferred)
> Key ID: 0x94620736
>





More information about the Python-list mailing list