Search code examples
pythonpython-black

How to structure a nested "x if condition else y" so Black will leave it legible?


For a double nested x if condition else y it was legible before black got into the fray. It loses the nice indentations I had placed and now it's just a Wall of Code:

        clause = (
            (f"{self.colname} " if self.colname else "") + self.sql
            if self.sql
            else self.values_filter()
            if self.values is not None
            and len(self.values) > 0
            and (self.colname is not None)
            else self.range_filter()
            if self.range is not None and (self.colname is not None)
            else None
        )

I'm going to break this into separate pieces for expediency but for legacy purposes would like to know if there's some way to get a legible format for this language construct.


Solution

  • Just put a pair of # fmt directives around code you don't want Black to reformat:

    # fmt: off
    ... your carefully formatted construct here ...
    # fmt: on