首页 > 解决方案 > What do I need to do to dynamically import a module?

问题描述

Can someone tell me why this doesn't work?

m = importlib.import_module('operator')
eval('operator.add') # returns NameError

I know I can use m.add but I can't do that as I am reading the input to eval from a file. Is there a way I can get m to be loaded into the current runtime?

标签: python

解决方案


You simply need to assign the result of import_module() to a variable named operator instead of m.

operator = importlib.import_module('operator')

Is equivalent to:

import operator

推荐阅读