Google Python Style Guide says:
Do not use relative names in imports. Even if the module is in the same package, use the full package name. This helps prevent unintentionally importing a package twice.
What would be a sample setup that incurs importing a package twice?
This is a reference to the Python 2 behavior (deprecated since 2.6) of implicit relative imports: allowing
import barin a module in a packagefooto refer to the modulefoo.bar. Consider a directory onsys.paththat looks likewith files having the following contents:
client.pypkg/__init__.pypkg/mod.pypkg/script.pyIn this setup
modcan easily be imported twice:In an attempt to reduce configuration overhead, Python adds the directory
pkgtosys.path, effectively presuming thatscript.pyis a top-level modulescript. Unfortunately, that means thatimport modcreates a top-level module namedmod, and the explicit import ofpkg.modlater causes another copy of it to exist with its full name (just after importingpkgitself).It was recognized that this poses a problem, and later
-mwas adjusted to tell the module being executed about the package in which it was found so that relative imports (implicit or explicit) work properly:Note that
pkgis now imported first (by-mitself!), thatscriptnow has a__package__attribute immediately afterwards, and thatmodis imported just once. Of course,scriptitself is (still) loaded twice, since its name gets replaced with__main__the first time so thatfrom pkg import scriptfinds it under a different name.The moral is that implementing "a module can also be a script" in terms of
__name__=='__main__'is fundamentally broken (and replacements have been rejected): a module already has a__name__, and creating a separate module object to be the entry point so that its__name__can differ is as absurd as copying the Java class (and all its static data) that providesmain. Making a module that no one ever imports works, but is oxymoronic (and breaks code inspection that imports all members of a package).