Search code examples
pythonpackagepython-importpython-module

Imports within an installed Python package


Consider the following directory structure for an installed Python package:

project/
    project/
        __init__.py
        file1.py
        file2.py
        module/
            __init__.py
            file3.py
    setup.py

In order to access a function in file2.py from file1.py, one could do

from file2 import fun

Or

from project.file2 import fun

Analogously, if from file1.py I wanted to access a function in file3.py, I could do from project.module.file3 import function or from .module.file3 import function.

These two options appear to be equivalent. Is there a preferred method, or a relevant difference between the two that I am missing?


Solution

  • Although this is mostly a matter of personal preference, PEP8 recommends using absolute imports:

    from project.module.file3 import function 
    

    rather than relative imports:

    from .module.file3 import function
    

    Absolute imports are more readable and better behaved (better error messages upon failure). BUT, when using absolute imports becomes unnecessarily verbose (use your judgement), using relative imports is an acceptable alternative. See this PEP8 documentation on imports.