Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String variable as import module specifier

I have tried the following:

>> modname = 'sys'
>> import modname
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: No module named modname

Why does import not recognize 'sys' as the name of the module to be imported?

like image 896
Marcos Gonzalez Avatar asked May 11 '26 18:05

Marcos Gonzalez


1 Answers

use importlib module if you want to import a module based on a string.

>>> import importlib
>>> mod = importlib.import_module('sys')
>>> mod
<module 'sys' (built-in)>
like image 83
Ashwini Chaudhary Avatar answered May 13 '26 09:05

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!