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

后端 未结 20 1713
醉酒成梦
醉酒成梦 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:58

    This is like many other optimizations - you sacrifice some readability for speed. As John mentioned, if you've done your profiling homework and found this to be a significantly useful enough change and you need the extra speed, then go for it. It'd probably be good to put a note up with all the other imports:

    from foo import bar
    from baz import qux
    # Note: datetime is imported in SomeClass below
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题