0

how do I achieve this,

imports = 'tensorflow torch requests re keyword builtins enum sys functools operator os itertools collections'.split()
import *imports

or

import imports

both fail

apostofes
  • 2,959
  • 5
  • 16
  • 31

2 Answers2

0

This seems strange, but you can achieve that by using exec()

exec(f"import {', '.join(imports)}")

Bear in mind that usage of exec() with users input is insecure

sudden_appearance
  • 1,968
  • 1
  • 4
  • 15
0

Actually there are two ways I can point:

  1. Using import_module function from importlib, the problem with this method is it will import the module and will store it in as a object, so you can use a variable to get the values, but can't call the module directly in code.
from importlib import import_module
imports = 'tensorflow torch requests re keyword builtins enum sys functools operator os itertools collections'.split()

modules = [import_module(lib) for lib in imports]
  1. Using exec, it's equivalent to call the imports in your code, and you'll be able to do the call of module functions, classes etc.
imports = 'tensorflow torch requests re keyword builtins enum sys functools operator os itertools collections'.split()

for module in imports:
    exec(f'import {module}')
tiov4d3r
  • 23
  • 7