Use 'import module' or 'from module import'?

前端 未结 19 2133
一向
一向 2020-11-21 07:47

I\'ve tried to find a comprehensive guide on whether it is best to use import module or from module import. I\'ve just started with Python and I\'m

19条回答
  •  不思量自难忘°
    2020-11-21 08:07

    import package
    import module
    

    With import, the token must be a module (a file containing Python commands) or a package (a folder in the sys.path containing a file __init__.py.)

    When there are subpackages:

    import package1.package2.package
    import package1.package2.module
    

    the requirements for folder (package) or file (module) are the same, but the folder or file must be inside package2 which must be inside package1, and both package1 and package2 must contain __init__.py files. https://docs.python.org/2/tutorial/modules.html

    With the from style of import:

    from package1.package2 import package
    from package1.package2 import module
    

    the package or module enters the namespace of the file containing the import statement as module (or package) instead of package1.package2.module. You can always bind to a more convenient name:

    a = big_package_name.subpackage.even_longer_subpackage_name.function
    

    Only the from style of import permits you to name a particular function or variable:

    from package3.module import some_function
    

    is allowed, but

    import package3.module.some_function 
    

    is not allowed.

提交回复
热议问题