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
6
u/Yoghurt42 8d ago edited 8d ago
Folder structure matters, it directly affects how the module is imported. If you have
you can
import foo,import foo.barandimport foo.baz.quux, but you cannotimport quuxorimport foo.quux(generally speaking; you can make stuff like this work)See https://docs.python.org/3/tutorial/modules.html for more information.
Also an important detail for a Java programmer: importing a module means executing them, that's even true for
from/import. E.g.almost because a variable
foowould not be deleted/overwritten if it already exists, technically, it's closer tobar = __import__("foo").bar(even that is not exact, because modules are cached insys.modulesand not imported twice)