Python importlib import_module Relative Import of Module
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
Jarad
I am many things. Programmer - Python primarily, trying to learn Javascript more Data scientist - machine learning with Python (Scikit-learn, Tensorflow, Keras, PyTorch, etc.) Entrepreneur - Build paid search software, creator of an index card sleeve (very useful next to your desk while you code), online course creator, paid advertising consultant and mentor, and so on.
Updated on June 04, 2022Comments
-
Jarad almost 2 years
According to this answer, you can use
importlib
toimport_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