jdborg jdborg - 5 months ago 6
Python Question

How to use python's import function properly __import__()

I'm trying to replicate

from foo.bar import object
using the
function and I seem to have hit a wall.

from glob import glob
is easy:
glob = __import__("glob",glob)
glob = __import__("glob").glob

The problem I'm having is that I am importing from a package (i.e. bar) and I want the script in the package to be the source of the import.

So what I'd like is something like

string_to_import = "bar"
object = __import__("foo",string_to_import).object

But this just imports the
in the foo package.

How can this be done?

When I use the obvious, only the
is called

<module 'foo' from 'foo/__init__.pyc'>


The import statement will return the top level module of a package, unless you pass the following additional arguments.

_temp = __import__('foo.bar', globals(), locals(), ['object'], -1) 
object = _temp.object

See Python docs on __import__ statement