Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, PEP-8 and multi-line dict formatting

Tags:

python

pep8

I have to declare some dict in Python. I write such a code:

class MegaClass(object):
    _activation_grad_classes = \
    {
        activation.ForwardStrictRELU: activation.BackwardStrictRELU,
        activation.ForwardLog: activation.BackwardLog,
        activation.ForwardSinCos: activation.BackwardSinCos
    }

And get a PEP-8 error: E122 continuation line missing indentation or outdented.

How can I fix it?

like image 232
Felix Avatar asked Jan 28 '26 05:01

Felix


1 Answers

Put the opening curly brace on the assignment line:

_activation_grad_classes = {
    activation.ForwardStrictRELU: activation.BackwardStrictRELU,
    activation.ForwardLog: activation.BackwardLog,
    activation.ForwardSinCos: activation.BackwardSinCos
}

There rarely is a need to use \ to escape a newline in Python; instead use {..}, [..] and (..) to group expressions across multiple lines.

like image 96
Martijn Pieters Avatar answered Jan 29 '26 18:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!