3

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?

2 Answers 2

5

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)>
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. It is a workaround (hence the upvote), but it does not quite answer my question, or does it not?
@MarcosGonzalez You can't do it with a string
@MarcosGonzalez import statement doesn't works with strings.
Why? It seems so 'intuitive' ;-)
@MarcosGonzalez There should be one way to do it
|
2
>>> modname = 'sys'
>>> sys = __import__(modname)

3 Comments

Thank you. It is a workaround (hence the upvote), but it does not quite answer my question, or does it not?
@MarcosGonzalez I suggesst you accept the answer by AshwiniChaudhary It is the current accepted way to do it
@MarcosGonzalez I wasn't aware of importlib when posting this ;)

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.