I want to import a file from subdir and I get an error like that:
ModuleNotFoundError: No module named 'special'
│
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── special
├── __init__.py
└── wantToImport.py =================>>>I want to import this file
My case.py like that:
from special.wantToImport import ImportClass
And my wantToImport.py file like that:
class ImportClass:
def mydefination(self):
#Some codes here
I want to use mydefinitioon function on my case.py file But I cannot import this file.
Why Im getting this error?
How can I solve this?
You should tell Python that your module's path is inside the current directory (using a .):
from .special.wantToImport import ImportClass
Try creating a __init__.py file in the directory where you are working and use it to refer your module.
│
root
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── __init__.py
├── special
├── __init__.py
└── wantToImport.py =================>>>I want to import this file
inport it using
from root.special.wantToImport import ImportClass
Related
In test_app, I have tried appending '../../src/app.py' to sys.path, from ...src.app import function or from app import function but I keep getting ModuleNotFoundError: No module named 'app'. Not sure how to overcome this seemingly simple issue.
├── src
│ └── app.py
├── tests
│ └── unit_tests
│ ├── __init__.py
│ ├── conftest.py
│ └── test_app.py
You need to add the full path to the parent folder, then import app:
import sys
sys.path.append("../../src")
# We can now directly access 'app' as we have a pointer to its parent directory
from app import function
# Use 'function' here
CONTEXT. Python 3.9.1, Flask 2.0.1 and Windows 10
WHAT I WANT TO DO. Call a module located inside a custom package.
TROUBLE. No matter what I do, the console insists on telling me: ModuleNotFoundError: No module named 'my_package'
WHAT AM I DOING.
I am following the official Flask tutorial https://flask.palletsprojects.com/en/2.0.x/tutorial/index.html. Therefore, the structure of the project is basically this (with slight changes from the tutorial):
/flask-tutorial
├── flaskr/
│ ├── __init__.py
│ ├── db.py
│ ├── schema.sql
│ ├── templates/
│ ├── static/
│ └── my_package/
│ ├── __init__.py (this file is empty)
│ ├── auth.py
│ ├── backend.py
│ ├── blog.py
│ └── user.py
├── venv/
├── .env
├── .flaskenv
├── setup.py
└── MANIFEST.in
Inside the file /flask-tutorial/flaskr/init.py I try to call the modules that contain my blueprints:
from my_package import backend
from my_package import auth
from my_package import user
from my_package import blog
backend.bp.register_blueprint(auth.bp)
backend.bp.register_blueprint(user.bp)
backend.bp.register_blueprint(blog.bp)
app.register_blueprint(backend.bp)
When I running the application (with the flask run command), the console tells me ModuleNotFoundError: No module named 'my_package', indicating that the problem is in the line where it is from my_package import backend.
HOW I TRIED TO SOLVE THE PROBLEM (unsuccessfully).
First. I have created an empty file called init.py inside 'my_package'
Second. Inside the file /flask-tutorial/flaskr/init.py, before the problematic FROM, I have put:
import os.path
import sys
parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent)
On the internet there are several posts with this same problem. Many of them mention that the solution is to put a init.py file inside the package (I already did this and it does not work for me). Also, unfortunately the structure of the projects in question is different from mine.
Any ideas how to fix this?
Change your code to
from .my_package import backend
from .my_package import auth
from .my_package import user
from .my_package import blog
backend.bp.register_blueprint(auth.bp)
backend.bp.register_blueprint(user.bp)
backend.bp.register_blueprint(blog.bp)
app.register_blueprint(backend.bp)
Just add a single dot . before the package name to import the package in the same parent package. In your case, __init__.py and my_package have a common flaskr as their parent package.
I have a project
testci/
├── __init__.py
├── README.md
├── requirements.txt
├── src
│ ├── __init__.py
│ └── mylib.py
└── test
├── __init__.py
└── pow_test.py
When I run python3.6 test/pow_test.py I see an error:
File "test/pow_test.py", line 3, in
import testci.src.mylib as mylib
ModuleNotFoundError: No module named 'testci'
pow_test.py
from testci.src.mylib import get_abs
def test_abs():
assert get_abs(-10) == 10
How can I fix this error?
System details: Ububntu 16.04 LTS, Python 3.6.10
try this
from .src import mylib
from mylib import get_abs
if it won't work then import one by one. But don't import the root folder since the file you are importing to is on the same folder you are trying to import then it will always raise an error
Run Python with the -m argument within the base testsci package to execute as a submodule.
I made a similar mock folder structure:
├───abc_blah
│ │ abc_blah.py
│ │ __init__.py
│
└───def
│ def.py
│ __init__.py
abc_blah.py
print('abc')
def.py
import abc_blah.abc_blah
Execute like such:
python -m def.def
Correctly prints out 'abc' as expected here.
simply add __package__ = "testci" and also it is a good practice to add a try and except block
Your final code should look something like
try:
from testci.src.mylib import get_abs
except ModuleNotFoundError:
from ..testci.src.mylib import get_abs
for running it, type python -m test.pow_test
I think your issue is how the package is installed. The import looks fine to me. As it says CI I'm guessing you're having the package installed remotely with only the test folder somehow.
Try adding a setup.py file where you define that both the test as well as the src packages are part of your testci package.
there are many ways to organize a project, keep things consider in mind, structure should be simple and more scaleable, can differentiate the things in codebase easily.
one of the few good possible ways to structure a project is below
project/
├── app.py
├── dockerfile
├── pipfile
├── Readme.md
├── requiements.txt
├── src_code
│ ├── code
│ │ ├── __init__.py
│ │ └── mylib.py
│ └── test
│ ├── __init__.py
│ └── test_func.py
└── travisfile
here app.py is main file which is responsible to run your entire project
I have a directory like
.
└── my_project
├── API
│ ├── __init__.py
│ └── admin.py
└── my_project
├── __init__.py
└── module1_file.py
Inside API/admin.py, I want to import func1 from my_project/module1_file.py. I do like this:
import sys
sys.path.insert(0, './myproject/myproject/')
from module1_file import func1
It throws me this error
from module1_file import func1
ModuleNotFoundError: No module named 'module1_file'
Can anyone please show me how to solve this? Thanks.
app structure:
.
├── Makefile
├── Pipfile
├── Pipfile.lock
├── README.md
├── template.yaml
├── tests
│ ├── __init__.py
│ └── unit
│ └── lambda_application
│ ├── test_handler.py
│ └── test_parent_child_class.py
└── lambda_application
├── __init__.py
├── first_child_class.py
├── lambda_function.py
├── second_child_class.py
├── requirements.txt
└── parent_class.py
4 directories, 14 files
Code sample from lambda_function.py:
import os
import json
from hashlib import sha256
import boto3
from requests import Session
from .first_child_class import FirstChildClass
def lambda_handler(event, context):
# Do some stuff.
As is, I get the error message
Unable to import module 'lambda_function'
but If I comment out the last import, from .first_child_class import FirstChildClass, it is able to get past that part and get the error that I haven't loaded the module for that class.
I only seem to get this error when I run it in the lambci/lambda:python3.7 docker image and when I deploy on AWS. All my tests pass and it is able to import the module with no problems.
Is there something I should load/setup in the __init__.py file?
EDIT I changed the names of some of the files to post it here.
You are using a relative import here which works in case the code you are executing is in a module. However, since your code is being executed not as a module, your AWS Lambda fails.
https://stackoverflow.com/a/73149/6391078
A quick run locally gave the following error:
PYTHON 3.6
Traceback (most recent call last):
File "lambda_function.py", line 4, in <module>
from .first_child_class import FirstChildClass
ModuleNotFoundError: No module named '__main__.first_child_class'; '__main__' is not a package
Your tests pass because your testing suite imports the file as a module from the lambda_application folder which gets treated as a package in the testing module
This got me going in the correct direction but didn't quite give me the answer but did lead me to the answer, so I thought I would update what I found here.
I didn't try it but from what I found, I believe that:
from first_child_class import FirstChildClass
would be the simplest resolution.
What I ended up doing was moving the classes into a sub-directory and essentially did the same as above but with a package name prepended.
So, the file structure changed to:
.
├── Makefile
├── Pipfile
├── Pipfile.lock
├── README.md
├── template.yaml
├── tests
│ ├── __init__.py
│ └── unit
│ └── lambda_application
│ ├── test_handler.py
│ └── test_parent_child_class.py
└── lambda_application
├── __init__.py
└── lib
├── first_child_class.py
├── second_child_class.py
└── parent_class.py
├── lambda_function.py
└── requirements.txt
and my import became from lib.first_child_class import FirstChildClass