Should import statements always be at the top of a module?

后端 未结 20 1616
醉酒成梦
醉酒成梦 2020-11-22 02:56

PEP 08 states:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.<

20条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:59

    There can be a performance gain by importing variables/local scoping inside of a function. This depends on the usage of the imported thing inside the function. If you are looping many times and accessing a module global object, importing it as local can help.

    test.py

    X=10
    Y=11
    Z=12
    def add(i):
      i = i + 10
    

    runlocal.py

    from test import add, X, Y, Z
    
        def callme():
          x=X
          y=Y
          z=Z
          ladd=add 
          for i  in range(100000000):
            ladd(i)
            x+y+z
    
        callme()
    

    run.py

    from test import add, X, Y, Z
    
    def callme():
      for i in range(100000000):
        add(i)
        X+Y+Z
    
    callme()
    

    A time on Linux shows a small gain

    /usr/bin/time -f "\t%E real,\t%U user,\t%S sys" python run.py 
        0:17.80 real,   17.77 user, 0.01 sys
    /tmp/test$ /usr/bin/time -f "\t%E real,\t%U user,\t%S sys" python runlocal.py 
        0:14.23 real,   14.22 user, 0.01 sys
    

    real is wall clock. user is time in program. sys is time for system calls.

    https://docs.python.org/3.5/reference/executionmodel.html#resolution-of-names

提交回复
热议问题