Ram Rachum
Ram Rachum

Reputation: 88508

Importing a submodule given a module object

I am given a module as an object, and I need to import a submodule from it. Like this:

import logging
x = logging

Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of the module.)

How do I do this? If I do import x.handlers it fails.

Upvotes: 6

Views: 3594

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

Try:

__import__('%s.handlers' % x.__name__)

Note that this will return a reference to logging, which you probably won't care about. It will create x.handlers though.

Upvotes: 5

Jan Tojnar
Jan Tojnar

Reputation: 5524

You can use built-in function __import__: http://docs.python.org/library/functions.html#import

Upvotes: 0

Related Questions