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)
2
  • I don't think so, it also might be a good approach to avoid confusion. I'll update my answer. Commented Jan 11, 2014 at 20:43
  • possible duplicate of Dynamic module import in Python Commented Jan 11, 2014 at 22:24

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Is true that import_module is more recommendable.
@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. :)
2

Use __import__ function:

x = 'sys'
sys = __import__(x)

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.