0

I try to import a module with exec("import __ as tmp") in python:

def prepare(self):
    for modName in self._config.modules.keys():
        print(locals())
        exec("import {} as tmp".format(modName))
        print(locals())
        self._moduleInst[modName] = tmp

Output is:

{'modName': 'time', 'self': <pyo.Server.Server object at 0x000001CA17DFB550>}
{'modName': 'time', 'self': <pyo.Server.Server object at 0x000001CA17DFB550>, 'tmp': <module 'time' (built-in)>}

Traceback (most recent call last):
    File "[...]", line 3, in <module>
        startServer(None)
    File "[...]", line 10, in startServer
        server.prepare()
    File "[...]", line 15, in prepare
        self._moduleInst[modName] = tmp
NameError: name 'tmp' is not defined

I get an NameError exception, cause python cannot find tmp. If I print out all local variables, tmp is defined...

Has anybody an idea what I'm doing wrong? Thank you!

user3422533
  • 305
  • 1
  • 6
  • 11
  • Edit: If I try the same in console it works outside a function, but in a function the same error happends... – user3422533 Nov 12 '17 at 10:40
  • Possible duplicate of [Behavior of exec function in Python 2 and Python 3](https://stackoverflow.com/questions/15086040/behavior-of-exec-function-in-python-2-and-python-3) – Davis Herring Oct 28 '18 at 18:04

2 Answers2

0

You don't declare tmp variable anywhere in your function code:

def prepare(self):
    for modName in self._config.modules.keys():
        print(locals())
        exec("import {} as tmp".format(modName))
        print(locals())
        self._moduleInst[modName] = vars()['tmp']

The tmp in your exec statement is a string. So I guess what you are trying to do is this: self._moduleInst[modName] = 'tmp', which saves the string tmp to your dict.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
0

Sorry, I seem unable to reproduce this. My code:

class foo:
    modules = { 'string' : 0 }

    def prepare(self):
        for modName in self.modules.keys():
            print(locals())
            exec("import {} as tmp".format(modName))
            print(locals())
            self.modl = tmp

somevar = foo()
somevar.prepare()
print(somevar.modl.digits)

Output:

{'modName': 'string', 'self': <__main__.foo instance at 0x7f5c11123128>}
{'tmp': <module 'string' from '/usr/lib/python2.7/string.pyc'>, 'modName': 'string', 'self': <__main__.foo instance at 0x7f5c11123128>}
0123456789

Difference in Python versions?

Vroomfondel
  • 2,704
  • 1
  • 15
  • 29