1

I want to create a function which uses import, like the following:

    def test_module(module_name):
            try:
                    import module_name
            except ImportError:
                    print 'import '+module_name+' error'


    test_module('os')

however, the function doesn't work because import seems not to recognize the string variable. are there any workarounds?

thanks!

0

1 Answer 1

2

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

1 Comment

(I did not downvote). Your syntax is wrong. It should be imported = __import__(module_name). That said, the preferred method is to use importlib.import_module.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.