I can use the following code to change a string to a variable and then call function of the library that was previously imported.
>>> import sys
>>> x = 'sys'
>>> globals()[x]
<module 'sys' (built-in)>
>>> globals()[x].__doc__
Without first importing the module, I have an string to variable but I can't use the same globals()[var]
syntax with import
:
>>> y = 'os'
>>> globals()[y]
<module 'os' from '/usr/lib/python2.7/os.pyc'>
>>> import globals()[y]
File "<stdin>", line 1
import globals()[y]
^
SyntaxError: invalid syntax
>>> z = globals()[y]
>>> import z
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named z
Is it possible for a string input and import the library that has the same name as the string input? If so, how?
@ndpu and @paulobu has answered that __import__()
allows string to library access as a variable. But is there a problem with using the same variable name rather than using an alternate for the library? E.g.:
>>> x = 'sys'
>>> sys = __import__(x)