Aviv Cohn
Aviv Cohn

Reputation: 17203

In a package, is there a way to directly access modules, not via the package name?

Consider a directory mypackage containing the files __init__.py, module_a.py and module_b.py.

If module_a wants to access module_b, it has to do import mypackage.module_b or import module_b from mypackage. Simply import module_b fails.

Firstly: why?

Secondly: is this a problem?

Thirdly: if it is, what's the best way to deal with this?

Upvotes: 0

Views: 35

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122352

Python 3 uses absolute imports; any unqualified name is seen as a top-level module or package.

If you want to import from within a package, use . relative package prefixes; . is the current package, .. the parent, etc.

So from within your mypackage package you can access other modules with:

from . import module_b

See the Intra-package References section of the Python tutorial and the import statement reference.

Upvotes: 3

Related Questions