I began to brush the dust off an old Python project by running the 2to3, a Python program that can automate code translation from Python 2 to 3. The first suggestion was to replace the import statement in a __main__ file as follows:

-from reference.wiktionary import Wiktionary
+from .reference.wiktionary import Wiktionary

This change was based on a fixer that “detects sibling imports and converts them to relative imports” (see Python documentation). An explanation for this fixer can be found in the Intra-package References article, which states, “Note that relative imports are based on the name of the current module. Since the name of the main module is always”__main__“, modules intended for use as the main module of a Python application must always use absolute imports.”

Absolute imports are explained by PEP 328, which states, “In Python 2.4 and earlier, if you’re reading a module located inside a package, it is not clear whether import foo refers to a top-level module or to another module inside the package. … foo will always be a module or package reachable from sys.path. This is called an absolute import.”

See also