Python: How To Use 'import' On Character String Variable?
I want to create a function which uses import, like the following: def test_module(module_name): try: import module_name except Impo
Solution 1:
imported = __import__(module_name)
will work.
Or you can use importlib.import_module
.
The difference is in convenience: in case of import like
module_name = 'top.lower'
__import__
will return top
, whereas importlib.import_module
will return lower
:
>>> __import__('os.path')
<module 'os'from nowhere>
>>> importlib.import_module('os.path')
<module 'ntpath'from nowhere>
Post a Comment for "Python: How To Use 'import' On Character String Variable?"