Importing modules in Python - best practice

后端 未结 6 545
时光取名叫无心
时光取名叫无心 2020-12-02 11:46

I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts.

What

6条回答
  •  爱一瞬间的悲伤
    2020-12-02 12:25

    Here are some recommendations from PEP8 Style Guide.

    1. Imports should usually be on separate lines, e.g.:

      Yes: import os
           import sys
      
      No:  import sys, os
      

      but it is okay to

      from subprocess import Popen, PIPE
      
    2. Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

      • Imports should be grouped in the following order:
        1. standard library imports
        2. related third party imports
        3. local application/library specific imports
      • You should put a blank line between each group of imports.
    3. Absolute imports are recommended
      They are more readable and make debugging easier by giving better error messages in case you mess up import system.

      import mypkg.sibling
      from mypkg import sibling
      from mypkg.sibling import example
      

      or explicit relative imports

      from . import sibling
      from .sibling import example
      
    4. Implicit relative imports should never be used and is removed in Python 3.

      No:  from ..grand_parent_package import uncle_package
      
    5. Wildcard imports ( from import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.


    Some recommendations about lazy imports from python speed performance tips.

    Import Statement Overhead

    import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.

    the given below is a scenario explained at the page,

    >>> def doit1():
    ... import string
    ... string.lower('Python')
    ...
    >>> import string
    >>> def doit2():
    ... string.lower('Python')
    ...
    >>> import timeit
    >>> t = timeit.Timer(setup='from __main__ import doit1', stmt='doit1()')
    >>> t.timeit()
    11.479144930839539
    >>> t = timeit.Timer(setup='from __main__ import doit2', stmt='doit2()')
    >>> t.timeit()
    4.6661689281463623
    

提交回复
热议问题