'import whole list using import once
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
Solution 1:[1]
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
Solution 2:[2]
Actually there are two ways I can point:
- 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]
- 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}')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sudden_appearance |
| Solution 2 | tiov4d3r |
