6

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
Community
  • 1
  • 1
Jarad
  • 17,409
  • 19
  • 95
  • 154

1 Answers1

4

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

Dany
  • 4,521
  • 1
  • 15
  • 32
jobou
  • 1,823
  • 2
  • 18
  • 28
  • 1
    What then is the point and purpose of `importlib.import_module()` ? If I have to import `sklearn.feature_extraction` anyways, why wouldn't I just import `sklearn.feature_extraction.text` in the head of the file? Do you have a good use-case of when to use `importlib.import_module`? – Jarad Jul 11 '16 at 18:56
  • importlib just provides the feature of the import statement in python code. – jobou Jul 11 '16 at 20:55
  • @Jarad you might not know the module name while writing the code. It can be read from some config file, for example. – LogicDaemon Aug 16 '22 at 07:28