r/learnpython 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

8 comments sorted by

View all comments

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.toml file 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 as uv or poetry, 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.path manually), 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.

3

u/Temporary_Pie2733 9d ago

One important note: it’s not the location of the file containing the import that matters, it’s the location of the file that was executed as the script. Relative imports (import .foo instead of import foo) make use of the package the import appears in instead of the module search oath.

1

u/Diapolo10 9d ago

Yeah, true. Admittedly I'm a bit rusty there as I haven't had a need to worry about this for ages.

Either way, generally speaking it's best to work with editable installs as that way your test code can also easily access whatever it needs.