black icon indicating copy to clipboard operation
black copied to clipboard

Imports inside functions should not have an empty line after them

Open CrazyPython opened this issue 1 year ago • 1 comments

I use imports inside functions to implement lazy module loading to improve startup time. Black reformats imports within functions by adding an additional empty line this way:

async def start_web_interface(app, port):
    import uvicorn

    uv_config = uvicorn.Config(app, port=port)
    server = uvicorn.Server(uv_config)
    return await server.serve()

Desired style

async def start_web_interface(app, port):
    import uvicorn
    uv_config = uvicorn.Config(self.app, port=port)
    server = uvicorn.Server(uv_config)
    return await server.serve()

Additional context The Black code style says:

Black avoids spurious vertical whitespace. This is in the spirit of PEP 8 which says that in-function vertical whitespace should only be used sparingly.

In some projects, it's common for all first-party modules to be imported, but based only some third-party modules are needed based on configuration or user input. For instance, a command-line tool may be typically used interactively but have the ability to start an optional web interface. Lazily importing the third-party web server module allows the command-line tool to respond faster for interactive use. Imports within functions and methods are one way of achieving lazy imports in a Pythonic way.

CrazyPython avatar Mar 06 '24 21:03 CrazyPython

Duplicate of https://github.com/psf/black/issues/2543

hauntsaninja avatar Mar 06 '24 21:03 hauntsaninja