JRR
JRR

Reputation: 6152

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?

Upvotes: 0

Views: 93

Answers (1)

Delgan
Delgan

Reputation: 19617

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

Upvotes: 4

Related Questions