Search code examples
pythonpython-importpython-module

How should package modules import from each other?


I have this package structure:

widget/
    __init__.py
    core.py
    extension.py

__init__.py is empty.

core.py contains this:

import widget.extension as extension

It works, but it feels like I'm side-stepping the package and just importing it from the global path (i.e. climbing out of it only to look back into it). If I just import extension in core.py it doesn't work. Does this matter? Am I wrong in the first place? Should I instead be pulling both of these modules into __init__.py?


Solution

  • I'm presuming you are using Python 3; in Python 2, import extension would work as Python 2 will first look for a local, relative import before looking for a global, absolute reference.

    You have two more options:

    from widget import extension
    

    and

    from . import extension
    

    The latter imports relative to the current package, which allows you to rename your widget package without having to update all your internal imports. What you use is a matter of style and taste.