2

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?

rhz
  • 960
  • 14
  • 29
  • Unfortunately, I think you can't. black i deterministic meaning it will always produce the same output for the same input (independent of whitespace). It calculates the context free grammar (CFG) of the python files, which removes all the whitespace and breaks the files down to only the statements. After that it rearranges the best it can to format it according to a pre-defined style. But there is not much possibility to interfere with the formatting. Here the creator of black explains how it works: https://youtu.be/esZLCuWs_2Y?t=493 – schilli May 19 '21 at 21:54
  • In case of such long import statements, I guess you just have to accept that the line exceeds the PEP8 line length, when you don't want to rearrange the file structure to flatten the hierarchy. If your linter complains, you could optionally silence that particular violation for this line. – schilli May 19 '21 at 22:01

2 Answers2

1

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
Michael Spranger
  • 485
  • 4
  • 11
0

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
Paul Lemarchand
  • 2,068
  • 1
  • 15
  • 27