[Python] Python alignment of assignments (style) [closed]

Discussão em 'Python' iniciado por Stack, Julho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I really like following style standards, as those specified in PEP 8. I have a linter that checks it automatically, and definitely my code is much better because of that.

    There is just one point in PEP 8, the E251 & E221 don't feel very good. Coming from a JavaScript background, I used to align the variable assignments as following:

    var var1 = 1234;
    var2 = 54;
    longer_name = 'hi';

    var lol = {
    'that' : 65,
    'those' : 87,
    'other_thing' : true
    };


    And in my humble opinion, this improves readability dramatically. Problem is, this is dis-recommended by PEP 8. With dictionaries, is not that bad because spaces are allowed after the colon:

    dictionary = {
    'something': 98,
    'some_other_thing': False
    }


    I can "live" with variable assignments without alignment, but what I don't like at all is not to be able to pass named arguments in a function call, like this:

    some_func(length= 40,
    weight= 900,
    lol= 'troll',
    useless_var= True,
    intelligence=None)


    So, what I end up doing is using a dictionary, as following:

    specs = {
    'length': 40,
    'weight': 900,
    'lol': 'troll',
    'useless_var': True,
    'intelligence': None
    }

    some_func(**specs)


    or just simply

    some_func(**{'length': 40,
    'weight': 900,
    'lol': 'troll',
    'useless_var': True,
    'intelligence': None})


    But I have the feeling this work around is just worse than ignoring the PEP 8 E251 / E221.

    What is the best practice?

    EDIT many years later

    Don't align. Sooner or later a new variable that is longer will come and your will have to hit spacebar here and there for a while until everything looks good again. Not worth it.

    EDIT even more years later Just use a code formatter like black and use it as pre-commit and/or your CI. Then forget about this.

    Continue reading...

Compartilhe esta Página