I'm trying to replicate from foo.bar import object using the __import__ function and I seem to have hit a wall.
from glob import glob is easy:
glob = __import__("glob",glob)or 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 __init__ in the foo package.
How can this be done?
EDIT:
When I use the obvious, only the __init__ is called
__import__("foo.bar")
解决方案
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