1

I am unable to dynamically import a module which I have no problem importing in code and I have no idea why.

I have the following:

> ls lib
__init__.py     main.py

The init file is empty. The following works:

> python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.main
>>> lib.main.sayyay()
yay

The following does not work:

> python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> importlib.import_module("lib.main")
<module 'lib.main' from '/some/path/lib/main.py'>
>>> lib.main.sayyay()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'lib' is not defined

I did read the importlib documentation as well as a couple of answers here on SO, e.g., How to import a module in Python with importlib.import_module and Dynamically import a method in a file, from a string

But what am I missing?

1 Answer 1

3

import_module returns the imported module. Therefore, you need to give the imported module a name and use this just like lib.main

>>> lib_main = importlib.import_module("lib.main")
>>> lib_main.sayyay()
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that was unexpected. But I see how this can be useful. Thank you.

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.