Home > Software engineering >  Why I can't import my own module in python?
Why I can't import my own module in python?

Time:12-23

I had trying a app using Flask. I'm used my package UsefulDeveloperTools. Its __init__.pylike this: (__init__.py)

"""
Useful Tools.
"""

import threads
import IDgenerator

And its directory is like this: (directories

.
\ __init__.py
\ threads.py
\ IDgenerator.py

And I pushed it in TestPyPI and installed it in my virtual environment used python3 -m pip install --upgrade --index-url https://test.pypi.org/simple/ --no-deps UsefulDeveloperTools.

And I have activated my environment, and run following code use python3 main.py: (main.py)

import flask
from threading import Thread
import time
import random
import UsefulDeveloperTools # Error this
import logging

app=flask.Flask(__name__)
# unimportance

But python raised an error: (terminal)

(Blog) phao@phao-virtual-machine:~/桌面/pypoj/Blog$ python3 main.py
Traceback (most recent call last):
  File "/home/phao/桌面/pypoj/Blog/main.py", line 5, in <module>
    import UsefulDeveloperTools
  File "/home/phao/桌面/pypoj/Blog/lib/python3.10/site-packages/UsefulDeveloperTools/__init__.py", line 5, in <module>
    import threads
ModuleNotFoundError: No module named 'threads'

Why? What wronged? How can I finish it?

P.S. This is my packages in my environment: (terminal)

(Blog) phao@phao-virtual-machine:~/桌面/pypoj/Blog$ pip list
Package              Version
-------------------- -------
click                8.1.3
Flask                2.2.2
itsdangerous         2.1.2
Jinja2               3.1.2
Markdown             3.4.1
MarkupSafe           2.1.1
pip                  22.3.1
setuptools           59.6.0
UsefulDeveloperTools 0.2.2
Werkzeug             2.2.2

CodePudding user response:

I guess your __init__.py is wrong. You have to put your package name in front of your module names within the innit.

Check out this article for different options for innit styles:
https://towardsdatascience.com/whats-init-for-me-d70a312da583

Edit I looked on your repo and you are not following the packaging guide at all. You should reorganize your code in a proper file structure and set up eg. a pyproject.toml.

CodePudding user response:

if you have made the module then keep it in the same directory as your file and run it.

  • Related