0

Lets say I have some function that gets called during runtime. In this function I want to import a module given a name as argument.

This is the basic idea. Essentially I have a directory full of scripts. I want to import the given script by name so that it can dynamically be used in my code without changing any variable names etc.

def some_func(PARAMATER):
    eval("exec('import Some." + PARAMATER + ".module as myModule')")

    module.test()

The error I get is:

NameError: name 'myModule' is not defined

I tested this code several time with different approaches. Whenever it is inside of a function block, I get an error. Whenever it is not, it works perfectly.

If there are any better ideas of dynamically loading a module and being able to change it during runtime, I would happily use another approach.

Paul Brink
  • 332
  • 1
  • 4
  • 21
  • If you import something within a function, its imported variables and such will all be local to that function. You won't be able to access them outside of that function. See: https://stackoverflow.com/questions/42288077/if-i-import-a-module-inside-a-function-will-the-variables-be-local If you want to import something while in a function and have it be global, [here](https://stackoverflow.com/questions/11990556/how-to-make-global-imports-from-a-function) is how. – Random Davis Jan 31 '22 at 18:09
  • Yes, but I am trying to call the method of the given function within the scope of the method importing the module – Paul Brink Jan 31 '22 at 18:12
  • Everything else aside - `exec` within `eval`? why not simply use `importlib`? – buran Jan 31 '22 at 18:12

0 Answers0