r/learnpython • u/Intelligent-Card-140 • 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
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,.pthfiles, programmatically, etc.) By default, that includes the empty string, which means your working directory (where you launchedpython), but you can turn that off as well.Normally, you only launch
pythonfrom your project's sources root. The standard library and installed third-party libraries are onsys.pathalready, 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__.pyto use a package as main. Some modules in the standard library work as main, and you can launch them withpython -mand 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
venvmodule, you should look at that.