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?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
BaCh
  • 625
  • 2
  • 5
  • 17

1 Answers1

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()
Mike Müller
  • 82,630
  • 20
  • 166
  • 161