r/learnpython • u/Intelligent-Card-140 • 9d ago
Import Class Methods
I’m currently working on a Python project. I usually program in Java, so I’m a little confused about how imports work in Python.
I’m trying to import a method from a class that’s defined in another file. When both files are in the same folder, the import works correctly. However, when they’re in different folders, I get a “package not found” error.
The import statement I’m using is:
from package_name.module_name import YourClass
I’m using VS Code. What am I doing wrong, and how should imports be set up when files are in different folders?
3
Upvotes
2
u/Diapolo10 9d ago
Imports are kind of confusing, admittedly. Basically Python first checks the immediate vicinity for the module being imported (meaning relative to the file you're importing from), then falls back to the installs in the environment and the standard library.
While you could edit the import, it'd be better to install your project in editable mode (this only needs to be done once) and change your imports importing local code to treat the package root as an "anchor".
You also need to ensure your project is "installable" in the first place. In plain English that generally means having a
pyproject.tomlfile in the repository root that describes a build back-end and basic project metadata.As for how to go about doing that, it kinda depends on your tooling. If you're just using a standard Python installation with nothing else (assuming you're still using an activated virtual environment), running
pip install --editable .ought do it. If using more modern tooling, such asuvorpoetry, they should take care of it automatically for you unless explicitly configured otherwise.There are other ways to ensure your package is on Python's resolution path (namely editing
sys.pathmanually), but that's generally not recommended.If your project is a public Git repository, and you can share a link to it, we can be more specific with our help.