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

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

    Here's an example where all the imports are at the very top (this is the only time I've needed to do this). I want to be able to terminate a subprocess on both Un*x and Windows.

    import os
    # ...
    try:
        kill = os.kill  # will raise AttributeError on Windows
        from signal import SIGTERM
        def terminate(process):
            kill(process.pid, SIGTERM)
    except (AttributeError, ImportError):
        try:
            from win32api import TerminateProcess  # use win32api if available
            def terminate(process):
                TerminateProcess(int(process._handle), -1)
        except ImportError:
            def terminate(process):
                raise NotImplementedError  # define a dummy function
    

    (On review: what John Millikin said.)

提交回复
热议问题