[ python ] importlib.import_module v.s. sys.modules

mod = sys.modules.get(module_name)

if not mod :

mod = importlib.import_module(module_name)

func= getattr(mod, function_name)

x = func(whatever_params)



The sys.modules attribute returns list of all the modules that **have been imported** so far in your environment.


We can import in absolute or relative terms.

Example : the module name can be ‘pkg.subpkg..mod’


ref : https://stackoverflow.com/questions/8790003/dynamically-import-a-method-in-a-file-from-a-string,




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s