Import a submodule based on 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.handlersusing only x, not the name "logging". (This is because I am doing dynamic import and will not know the name of the module.)

How should I do it? If I do import x.handlers, he fails.

+5
source share
2 answers

Try:

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

Note that this will return a link to loggingthat you probably don't care about. He will create x.handlers, though.

+5
source

All Articles