Imports inside functions should not have an empty line after them
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.
Duplicate of https://github.com/psf/black/issues/2543