Home > Mobile >  Python - Space before and after operators like =, , - etc
Python - Space before and after operators like =, , - etc

Time:07-29

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 im working on a Django Project and i want to include a .html document with a keyword.

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

If i run it like 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 an other way?

Thank you in advance.

CodePudding user response:

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.)

CodePudding user response:

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.

CodePudding user response:

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

  • Related