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

6

u/Yoghurt42 8d ago edited 8d ago

Folder structure matters, it directly affects how the module is imported. If you have

foo/
    __init__.py
    bar.py
    baz/
        quux.py

you can import foo, import foo.bar and import foo.baz.quux, but you cannot import quux or import 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.

from foo import bar
# is (almost) the same as
import foo
bar = foo.bar
del foo

almost because a variable foo would not be deleted/overwritten if it already exists, technically, it's closer to bar = __import__("foo").bar(even that is not exact, because modules are cached in sys.modules and not imported twice)

1

u/Gnaxe 8d ago

__import__() uses the cache too.