bgusach bgusach - 1 year ago 154
Python Question

Python alignment of assignments (style)

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,

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

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


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.


Best practice is subjective, but the most common practice is to stick to PEP8.

I definitely don't suggest creating dictionaries every time you want to call a function with named arguments. That's quite wasteful. I don't see why your original some_func call wouldn't work. I definitely break my function calls into lines if they get too long and unwieldy. But I do not align them. I imagine that the reason for the recommendation is because it can get to be a huge pain to maintain all of the spacing correctly over time, and the consensus was maintainability over the gain in prettyness.

If you're working on your own code, align away, who cares? PEP8 is a guideline, not a law.