pythonpython-importpep

Python best practice: how to alias a module


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?


Solution

  • 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:

    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.