I am using a package pkg
that has a submodule module_with_long_name
. This module is imported by pkg
, so I can use module_with_long_name
without explicitly importing it:
import pkg
pkg.do_stuff()
pkg.module_with_long_name.do_other_stuff()
But I want to alias this module since it has a long name, and I can't find any PEP convention saying which of the two following is best practice:
import pkg
# First way
from pkg import module_with_long_name as module
# Second way
module = pkg.module_with_long_name
Do you know any reference on this issue?
I would recommend always using the form:
import package_name.subpackage_name.module_name as pkg_mod_abbrev
where pkg_mod_abbrev
is an abbreviation that is suitable for the current module. This approach:
aligns all import
statements in the same way, independently of whether they rename the imported item (i.e., whether they contain the keyword as
). This improves readability.
keeps the import path contiguous. This is more readable. Writing from package_name.subpackage_name import module_name as pkg_mod_abbrev
splits the module name from the other part of the import path. This requires skipping the import
keyword that occurs between the first part of the import path, and the module name. Reading that would require more time.
encourages either:
package_name.subpackage_name.module_name
), orpkg_mod_abbrev
)and thus avoiding using module_name
(writing import package_name.subpackage_name.module_name as module_name
is still possible, but writing an as
renaming would likely by itself prompt choosing a suitable abbreviation; whereas from
... import
would define module_name
in absence of aliasing using as
).
Hiding the imported module _pkg_mod_abbrev
is useful, more so for cases where the name of the module would coincide with a name that is convenient to be used for variables (also this PEP 8 section).
For example, bdd
abbreviates "Binary Decision Diagram". The package dd
has a module named bdd
. It is convenient to name bdd
Python variables that are instances of the class dd.bdd.BDD
. Nonetheless, it is convenient to also name "bdd" the module dd.bdd
. Hiding the imported module enables both, while also improving introspection:
import dd.bdd as _bdd
def _main():
bdd = _bdd.BDD()
if __name__ == '__main__':
_main()
By PEP 8, imported names are an implementation detail. So even when unhidden, they are not part of the module's API.