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
1
  • What do you mean by "doesn't work"? Commented Jul 11, 2016 at 15:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
importlib just provides the feature of the import statement in python code.
@Jarad you might not know the module name while writing the code. It can be read from some config file, for example.

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.