black won't respect line length limits on long import statements

Viewed 243

Consider the following import statement:

from modeling.estimation.performance_analysis.monte_carlo.least_squares.error_grids import BaseGrid

black (with an 80 character/line limit) formats this as:

from modeling.estimation.performance_analysis.monte_carlo.least_squares.error_grids import (
    BaseGrid,
)

which goes beyond 80 characters. Any attempt to break up the import statement using \'s is undone by black.

How can I get black to respect the 80 character limit?

2 Answers

This is very inconvenient indeed. You can explicitly prevent black from formatting the import like

# fmt: off
from modeling.estimation.performance_analysis.monte_carlo.least_squares.\
    error_grids import BaseGrid
# fmt: on

Please try the following:

If BaseGrid is a function:

package = "modeling.estimation.performance_analysis.monte_carlo.least_squares"
name = "error_grids"
BaseGrid = getattr(__import__(package, fromlist=[name]), name).BaseGrid

BaseGrid()

If BaseGrid is a python file (splitted the String to respect the line length restriction) :

p = "modeling.estimation.performance_analysis"
p2 = "monte_carlo.least_squares.error_grids"
name = "BaseGrid"
BaseGrid = getattr(__import__(p + '.' + p2, fromlist=[name]), name)

This uses the __import__ function to import into a variable instead of using the import statement, and should be equivalent to :

from modeling.estimation.performance_analysis.monte_carlo.least_squares.error_grids import BaseGrid as BaseGrid
Related