简体   繁体   中英

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?

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 (ie, 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:

    • using the full import path inside the module (ie, package_name.subpackage_name.module_name ), or
    • creating an abbreviation that is suited to the current module (ie, pkg_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, which 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM