Search code examples
pythonpython-3.xpep8code-structure

What's the proper way to (PEP8)line break for when constants are called from a function?


I'm using spyder and I have a code which goes something like this

    detector_x, detector_y, smeared_x, smeared_y = gamma_detection(decay_positions, cos_theta, phi)

For which the second i in decay_positions exceeds the recommended amount of characters in a line(something like 90). I have the dynamical PEP8 analysis on so it naturally gives me warning for my code analysis. So what is the correct PEP8 way to do in this case? Is it

detector_x, detector_y, smeared_x, smeared_y = \
gamma_detection(decay_positions, cos_theta, phi)

which technically still runs but it's giving me warning

E122 continuation line missing indentation or outdented

or is it

detector_x, detector_y, smeared_x, smeared_y = gamma_detection(
    decay_positions, cos_theta, phi)

or is it

detector_x, detector_y, smeared_x, smeared_y = gamma_detection(
                                        decay_positions, cos_theta, phi)

Solution

  • You offered options {1, 2, 3}.

    Definitely use 2 or 3. It's a matter of taste between them, or what your favorite editor encourages you to use. (Put it all on one line with cursor past the open paren, hit RETURN, and use the suggested indentation.) As long as

    $ flake8
    

    does not complain, you're golden. (Get it with pip install flake8.)

    For lots of parameters, or parameters that involve lengthy expressions, you might even consider listing one param per line.

    If you're assigning to lots of long identifiers, you might consider surrounding the LHS in parens for the tuple unpack:

    (detector_x, detector_y,
     smeared_x, smeared_y) = gamma_detection(
        decay_positions,
        cos_theta + epsilon * some_long_expression(),
        phi)