0

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?

Bikramjeet Singh
  • 681
  • 1
  • 7
  • 22
JRR
  • 6,014
  • 6
  • 39
  • 59

1 Answers1

4

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
Delgan
  • 18,571
  • 11
  • 90
  • 141
  • What if I am importing something else rather than operator? For instance: `m = importlib.import_module(read_input())` – JRR Dec 25 '19 at 07:53
  • @JRR In such a case, it's more complicated as you have to dynamically assign a local variable. See: [Dynamically set local variable](https://stackoverflow.com/questions/8028708/dynamically-set-local-variable) So, it will look like `module = read_input()` and then `locals()[module] = importlib.import_module(module)`. – Delgan Dec 25 '19 at 07:56