safetyduck
safetyduck

Reputation: 6834

dynamically import submodules in python

Suppose I provide a module in the command line and want to import it using the "imp" module:

$ foo.py mod.a.b.c

What is the proper way of doing this?

Split the "mod.a.b.c" and add each path? The behaviour of "imp" does not seem to be parallel to "import".

Upvotes: 2

Views: 748

Answers (1)

unutbu
unutbu

Reputation: 879093

Given a module path as a string (modulename), you can import it with

module = __import__(modulename,fromlist='.') 

Note that __import__('mod.a.b.c') returns the package mod, while __import__('mod.a.b.c',fromlist='.') returns the module mod.a.b.c.

Upvotes: 5

Related Questions