0

If I have a file called input_file.py and I want to import some variables into another script I use the following:

from input_file import (VarA, VarB, VarC)

If I wanted to have the file name itself be a variable which I could easily switch how would I do it? As an example:

file_name = 'input_file'

from file_name import (VarA, VarB, VarC)
SiHa
  • 7,830
  • 13
  • 34
  • 43
Chris L
  • 319
  • 1
  • 3
  • 10
  • 1
    Possible duplicate of [Dynamic module import in Python](https://stackoverflow.com/questions/301134/dynamic-module-import-in-python) – Matthew Moore Jul 17 '18 at 20:38

1 Answers1

0

It is not recommended to clutter/clobber the global namespace and you should look at what @MatthewMoore pointed to.

Having said that, you can do this:

import importlib
globals().update(importlib.import_module(file_name).__dict__)

More details here.

swiftg
  • 346
  • 1
  • 9