ModuleNotFoundError in Python 3.8.3 - python-3.x

I've a problem with the importations of modules in Python. I'm doing a project with PyQt and I'm trying to refactor and restructure it.
The hierarchy is the next:
./main.py
./logic/__init__.py
./logic/transforms.py
./logic/hopfield.py
./gui/__init__.py
./gui/interface.py
./gui/mplwidget.py
./img
The error:
Traceback (most recent call last):
File "...\main.py", line 5, in <module>
from gui.interface import Ui_MainWindow
File ...\gui\interface.py", line 215, in <module>
from mplwidget import MplWidget
ModuleNotFoundError: No module named 'mplwidget'
The file interface.py
class Ui_MainWindow(object):
.
.
.
from mplwidget import MplWidget
The file main.py
import sys
import matplotlib
import numpy as np
from gui.interface import Ui_MainWindow
from gui.weightMatrix import Ui_Dialog
from gui.table import TableModel
from logic.hopfield import learn, searchPattern
from logic.transforms import transformVector, transformVectors
from PyQt5 import QtCore, QtGui, QtWidgets
class Actions(Ui_MainWindow):
def __init__(self):
.
.
.
I don't understand why it doesn't work, since inside the module if I run the interface file it works fine together with mplwidget as a module.

File ...\gui\interface.py", line 215, in
from mplwidget import MplWidget
your interface.py should have
absolute import:
from gui.mplwidget import MplWidget
or
relative import:
from .mplwidget import MplWidget
In addition, a great blog that explains the two different imports

Related

How to resolve SystemError: initialization of _internal failed without raising an exception?

Problem
I have written a code that takes some historical data as input. Assuming dataset has a timeseries format, I am trying to do a regression and find a predictor.
Code
For my project, I have four files: my_project.py, utilities.py, plotter.py, and constants.py. Here is some small portions (relevant imports) of the two scripts:
my_project.py:
from time import perf_counter
from constants import (output_dir, DATAPATH, output_file)
from utilities import (dataframe_in_nutshell, excel_reader, info_printer, sys, module_creator, process_discovery, data_explanatory_analysis, excel_reader, df_cleaner, feature_extractor, ml_modelling)
from plotter import Plotter
utilities.py
import os
import sys
import inspect
from pathlib import Path
from typing import (Iterable, List, Tuple, Optional)
from itertools import zip_longest
import matplotlib.pyplot as plt
import statsmodels.tsa.api as smt
import statsmodels.api as sm
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import scale
from pycaret.regression import (setup, compare_models, predict_model, plot_model, finalize_model, load_model)
import csv
from constants import (np, Path, nan_value, plots_dir, HOURS_PER_WEEK, LAGS_STEP_NUM, rc_params, NA_VALUES, COLUMNS_NAMES, string_columns, LAGS_LABELS, numeric_columns, output_dir, DATAPATH, dtype_dict, train_size)
from pprint import PrettyPrinter
pp = PrettyPrinter()
import seaborn as sns
sns.set()
Error Message
Traceback (most recent call last):
File "c:\Users\username\OneDrive\Desktop\project\my_project.py", line 10, in <module>
from utilities import (dataframe_in_nutshell, excel_reader, info_printer, sys, module_creator,
File "c:\Users\username\OneDrive\Desktop\project\utilities.py", line 18, in <module>
from pycaret.regression import (setup, compare_models, predict_model, plot_model, finalize_model,
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pycaret\regression.py", line 10, in <module>
import pycaret.internal.tabular
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pycaret\internal\tabular.py", line 48, in <module>
import pycaret.internal.preprocess
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pycaret\internal\preprocess.py", line 27, in <module>
from pyod.models.knn import KNN
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pyod\__init__.py", line 4, in <module>
from . import utils
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pyod\utils\__init__.py", line 4, in <module>
from .stat_models import pairwise_distances_no_broadcast
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pyod\utils\stat_models.py", line 11, in <module>
from numba import njit
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\numba\__init__.py", line 42, in <module>
from numba.np.ufunc import (vectorize, guvectorize, threading_layer,
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\numba\np\ufunc\__init__.py", line 3, in <module>
from numba.np.ufunc.decorators import Vectorize, GUVectorize, vectorize, guvectorize
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\numba\np\ufunc\decorators.py", line 3, in <module>
from numba.np.ufunc import _internal
SystemError: initialization of _internal failed without raising an exception
Logistics
I am running my_project.py in visual studio code on a Windows 10 machine.
All packages are based on Python 3.10 using conda-forge channel
Research
The following pages seem to explain a workaround but I am not sure if I am understanding the issue in here. I would appreciate if you can help me figure this out.
Error on import with numpy HEAD
Update ufunc loop signature resolution to use NumPy
Remove reliance on npy_ ufunc loops.
I had this very same issue today.
Solved it by downgrading Numpy to 1.23.1
So: pip install numpy==1.23.1

Pytest Error while Import "matplotlib.backends.backend_qt5agg" - pytest-qt

I have a created test file, test_sample.py. In that file I am trying to import the matplotlip package matplotlib.backends.backend_qt5agg, while running the pytest command it shows the following error. When I comment that import line, the pytest command will run successfully. But I should import that line.
test_sample.py file,
from PyQt5 import QtCore, QtGui, QtTest, QtWidgets
from PyQt5.QtCore import QCoreApplication, QObject, Qt
from PyQt5.QtWidgets import *
from pytestqt.plugin import QtBot
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
def test_method(self):
--------------
all the code
----------------
The following error,
test_sample.py:8: in <module>
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
..\esd_env\lib\site-packages\matplotlib\backends\backend_qt5agg.py:7: in <module>
from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611
..\esd_env\lib\site-packages\matplotlib\backends\backend_qtagg.py:12: in <module>
from .backend_qt import QtCore, QtGui, _BackendQT, FigureCanvasQT
..\esd_env\lib\site-packages\matplotlib\backends\backend_qt.py:72: in <module>
_MODIFIER_KEYS = [
..\esd_env\lib\site-packages\matplotlib\backends\backend_qt.py:73: in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
E TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
I don't know why it end up with this error. This import works successfully when I run the application. It cause an error only on running testcases using commandpytest.
Note I have installed matplotlip==3.6.0
Kindly help me to fix this issue.

ImportError: cannot import name 'StringIO'

I am trying to get data from yahoo of stocks of a company through the code.
But i am getting an ImportError at pandas_datareader.data where is says
ImportError: cannot import name 'StringIO'
Please help
I am new to this...and already spent 4 hrs but could not resolve.
I have even tried
import io
from io import StringIO
still getting the same error..!!
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
start = dt.datetime(2018,1,1)
end = dt.datetime(2018,12,31)
df = web.datareader('TSLA','yahoo',start,end)
print(df.head(5))
Error:-
Traceback (most recent call last):
File "C:\Users\JAILANCHAL\Desktop\tut.py", line 5, in <module>
import pandas_datareader.data as web
File "C:\Users\JAILANCHAL\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas_datareader\__init__.py", line 2, in <module>
from .data import (DataReader, Options, get_components_yahoo,
File "C:\Users\JAILANCHAL\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas_datareader\data.py", line 7, in <module>
from pandas_datareader.av.forex import AVForexReader
File "C:\Users\JAILANCHAL\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas_datareader\av\__init__.py", line 3, in <module>
from pandas_datareader.base import _BaseReader
File "C:\Users\JAILANCHAL\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas_datareader\base.py", line 11, in <module>
from pandas.compat import StringIO, bytes_to_str
ImportError: cannot import name 'StringIO'

Cyclic import in Python3

I have the following directory structure:
my-game/
__init__.py
logic/
__init__.py
game.py
player.py
game.py and player.py have import dependency on each other (cyclic imports).
game.py has the following definition.
from logic.player import RandomPlayer, InteractivePlayer
T = 8
class Game:
def __init__(self, p1, p2)
...
# some other things
if __name__ == '__main__':
p1 = RandomPlayer()
p2 = InteractivePlayer()
g = Game(p1, p2)
...
player.py is as follows:
from logic.game import T
class Player:
def __init__(self):
...
class RandomPlayer(Player):
def __init__(self):
...
class InteractivePlayer(Player):
def __init__(self):
...
I am trying to run the game from logic/ directory but I get the following error.
$ python3 game.py
Traceback (most recent call last):
File "game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
I then tried running game.py from the directory higher up (my-game/).
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
What am I doing wrong? How can I make these cyclic imports work?
I have also tried using this import in player.py
from .game import T
and using
from .player import RandomPlayer, InteractivePlayer
in game.py.
In this case, I get a different error. For example, when running from my-game/,
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package
I get a similar error when running from logic/ directory.
I looked at this post but didn't understand where I was going wrong.
You are made a circulair import in your code try to remove it from your import
Vist this link you can find some other info about circular import :Remove python circular import

I am getting this error "No module named 'darkflow.cython_utils.cy_yolo_findboxes'" When I am using darknet

When I try to use Pycharm to play with YOLO, I got the error.
Here is what I got, Any help will be appreciated.
Node: I have done python3 setup.py build_ext --inplace. All the file like cy_yolo_findboxes.c and cy_yolo2_findboxes are all inside the cython_utils folder. But it does not work.
import cv2
import sys
sys.path.append('/Users/hantaoliu/darkflow-master')
import tensorflow as tf
from darkflow.net.build import TFNet
import numpy as np
import time
option = {
'model': 'cfg/yolo.cfg',
'load': 'bin/yolo.weights',
'threshold': 0.15,
'gpu': 1.0
}
capture = cv2.VideoCapture('videofile1.mp4')
colors =[tuple(255 * np.random(3)) for i in range(5)]
for color in colors:
print(color)
Here are the error message
Traceback (most recent call last):
File "/Users/hantaoliu/PycharmProjects/YOLO/sample.py", line 5, in <module>
from darkflow.net.build import TFNet
File "/Users/hantaoliu/darkflow-master/darkflow/net/build.py", line 7, in <module>
from .framework import create_framework
File "/Users/hantaoliu/darkflow-master/darkflow/net/framework.py", line 1, in <module>
from . import yolo
File "/Users/hantaoliu/darkflow-master/darkflow/net/yolo/__init__.py", line 2, in <module>
from . import predict
File "/Users/hantaoliu/darkflow-master/darkflow/net/yolo/predict.py", line 7, in <module>
from ...cython_utils.cy_yolo_findboxes import yolo_box_constructor
ImportError: No module named 'darkflow.cython_utils.cy_yolo_findboxes'
Build the cython module
cd ./cython_utils
python3 setup.py build_ext --inplace

Resources