Python importlib import_module Relative Import of Module

Jarad picture Jarad · Jul 11, 2016 · Viewed 10.3k times · Source

According to this answer, you can use importlib to import_module using a relative import like so:

importlib.import_module('.c', 'a.b')

Why doesn't relative import work for sklearn.feature_extraction.text ?

importlib.import_module('.text', 'sklearn.feature_extraction')

I verified that text is a module with:

from types import ModuleType
import sklearn.feature_extraction.text
isinstance(sklearn.feature_extraction.text, ModuleType)

Returns

True

Edit

By "doesn't work", I mean it doesn't import the module.

I am using Python 3.4

Absolute way works:

import importlib
text = importlib.import_module('sklearn.feature_extraction.text')
tfidf = text.TfidfVectorizer()

Relative way doesn't:

import importlib
text = importlib.import_module('.text', 'sklearn.feature_extraction')
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    text = importlib.import_module('.text', 'sklearn.feature_extraction')
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2249, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2199, in _sanity_check
SystemError: Parent module 'sklearn.feature_extraction' not loaded, cannot perform relative import

Answer

jobou picture jobou · Jul 11, 2016

The parent module needs to be imported before trying a relative import.

You will have to add import sklearn.feature_extraction before your call to import_module if you want it to work.

Nice explanation here : https://stackoverflow.com/a/28154841/1951430