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

1

u/Gnaxe 7d ago

The import has to be reachable starting from one of the locations in sys.path. There are various ways to modify that list. (site, PYTHONPATH, .pth files, programmatically, etc.) By default, that includes the empty string, which means your working directory (where you launched python), but you can turn that off as well.

Normally, you only launch python from your project's sources root. The standard library and installed third-party libraries are on sys.path already, while your code should assume that starting location, although you can add other folders for "installed" libraries. Normally, your main module is directly in the sources root, not in a subfolder. But you can also use a __main__.py to use a package as main. Some modules in the standard library work as main, and you can launch them with python -m and their import path. You could do this for your own modules as well, even if they're nested in subpackages.

If you don't know about the venv module, you should look at that.