advanced points from open source python projects

来源:互联网 发布:linux修改dns地址 编辑:程序博客网 时间:2024/06/07 05:07

mainly for open source mongoengine

(1)fallback import

(2)import from the future

(3)customize imports by _ _ all _ _
the situation: sometimes, it does not make much sense that exporting utility functions and classes to external code. in order to control what objects get exposed when you import a module like this, you can specify _ _ all _ _ somewhere in this module.

All that you need to do is supply a listor some other sequence—that contains the names of objects that should get imported when the module is imported using an asterisk(*)

#module a__all__ = ['func1']def func1():    returndef func2():    return 0#module bfrom a import *func1() #OKfunc2() #NOK

(4)absolute/relative(intra-package) import
  about imports in Python PEP328(multiple-lines,absolute/relative) and PEP338(executing modules as scripts) and PEP366(main modules explicit relative imports)
   (a)absolute import
For example, the statement import pkg_or_module_name may be ambiguous.
To resolve ambiguity, it is proposed that pkg_or_module_name will always be a module or package reachable from sys.path, which is called an absolute import.
   (b)relative import
Note: it is some difficulty to directly execute a module with relative import as a top-level script

(5)script&module
a python files may be loaded in two styles, either as a top-level script or as a module.

原创粉丝点击