Python: space before and after operators like =, +, -, etc

1.6k views Asked by At

Following the PEP 8 rules for Python, you should use spaces before and after operators, for example, x = 1 + 2. I follow this convention, and I don't like it without spaces.

Currently, I'm working on a Django project, and I want to include an HTML document with a keyword.

> {% include "pagination.html" with page = shares %}

If i run it as written above I get a keyword error:

"with" in 'include' tag needs at least one keyword argument.

Without the spaces before and after the = it works without problems. Is that the only way, or is there another way?

3

There are 3 answers

1
Omri Madar On

There are some cases in which you should not use spaces, like when setting default values to function parameters, or when passing kwargs (keyword arguments), like in your case.

See: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements

0
Gagan Garg On

No, you have to remove spaces before and after = operator because, it you add space between argument name & = & argument value, interpreter can't differentiate the arguments, it gets the argument name but don't find the value.

so you have to remove the spaces after and before operator = , to let interpreter know it is the argument provided.

0
Stephen C On

As noted, this is Django template language not real Python, so Python style rules do not apply.

However, I would argue that page=shares in

{% include "pagination.html" with page=shares %}

is a named parameter binding rather than an assignment. As such, it is consistent with this Python:

self.someMethod(1, 2, someFlag=True)

PEP style rules say that there should NOT be spaces around the = in a parameter binding. It is not an operator in that context.

But either way, the template language is what it is. Take it or leave it.


Is that the only way or is there an other way?

AFAIK, it is the only way. (And the right way, IMO.)