__import__() with packages

Paul Moore pf_moore at yahoo.co.uk
Sun Apr 4 11:23:38 EDT 2004


Marco Herrn <herrn at gmx.net> writes:

> I am using the builtin __import__() to import modules. That works for
> simple modules like in this example:

[...]

> But how do I do this with packages? A I understand the documentation
> for __import__(), it must be something like:

Look again at the documentation for __import__. In particular, you
want a function like the following, given in the dicumentation:

def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

Then, you do

    eggs = my_import("spam.eggs")

I have to admit, I find this annoyingly subtle - 99.99% of the time,
it's my_import() that you want, but you have to define it yourself...

Ah, well. I hope this helps.

Paul
-- 
This signature intentionally left blank



More information about the Python-list mailing list