2

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)
alvas
  • 115,346
  • 109
  • 446
  • 738

3 Answers3

4

Most Python coders prefer using importlib.import_module instead of __import__:

>>> from importlib import import_module
>>> mod = raw_input(":")
:sys
>>> sys = import_module(mod)
>>> sys
<module 'sys' (built-in)>
>>> sys.version_info # Just to demonstrate
sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)
>>>

You can read about the preference of importlib.import_module over __import__ here.

  • +1 Is true that `import_module` is more recommendable. – Paulo Bu Jan 11 '14 at 20:45
  • 1
    @alvas - Because `__import__` is a very advanced built-in that is mainly used to customize the way Python imports modules. If your goal is simply to import a module from a string, it is better to use a function built explicitly for that. Note however that this is a _preference_ of Python coders. Kinda like how list comprehensions are generally preferred over functional programming with `map`. You can still use `__import__` if you really want to. :) –  Jan 11 '14 at 21:03
2

Use __import__ function:

x = 'sys'
sys = __import__(x)
ndpu
  • 22,225
  • 6
  • 54
  • 69
1

You are looking for __import__ built-in function:

__import__(globals()[y])

Basic usage:

>>>math = __import__('math')
>>>print math.e
2.718281828459045

You can also look into importlib.import_module as suggested in another answer and in the __import__'s documentation.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73