Search code examples
pythoncode-organization

How to properly format long lines in Python?


I'm sure we're all familiar with PEP 8, and its specification for line length. Unfortunately, mathematics exists.

I am trying to write REALLY long equations in Python (Trig, Surface area of complex shapes, etc.) and I would like to be able to retain clarity in my formulas without breaking up my lines too much.

For example, this formula is pretty long, and might be indented many times in my code, leaving me not much room to work with:

    slantHeight = ((math.sqrt(((baseSideLength/2) * (baseSideLength/2)) + heightSquared))

What's the recommended way to break up this line?


Solution

  • You can do this:

    slantHeight = math.sqrt(
        (  # halfBaseSideLengthSquared
            (  # halfBaseSideLength
                baseSideLength / 2) *
            (baseSideLength / 2)) +
        (  # heightSquared
            height * height))
    

    Or this:

    def _(name, x):
        return x
    
    slantHeight = math.sqrt(_('halfBaseSideLengthSquared', _('halfBaseSideLength', baseSideLength / 2) * (baseSideLength / 2)) + _('heightSquared', height * height))
    

    You can even remove the name argument since it's ignored, though I can't see how this'll help with anything.

    I recommend you stop worrying so much about file size and focus on readability. Extra lines will not hurt. Something like this:

    halfBaseSideLength = (.5 * baseSideLength)
    halfBaseSideLengthSquared = (halfBaseSideLength * halfBaseSideLength)
    

    is useful because it reduces duplication, although the better thing to do would be:

    halfBaseSideLengthSquared = (.5 * baseSideLength) ** 2