0

Django, for example, uses this code to cater for ValidationError exceptions

>>> message = 'My name is %(name)s'
>>> params = {'name': 'George'}
>>> message %= params
>>> print(message):
'My name is George'

The only documentation I managed to find on %= is here where it is called a modulus assignment operator.

I really do not understand why it works with the old style formatting (%) and I cannot understand how this will be used with the new style formatting (str.format()).

Does the new style formatting render this code redundant?

raratiru
  • 8,748
  • 4
  • 73
  • 113
  • 1
    just looks lazy to me. But ` x %= y ` is essentially equivalent to `x = x%y` so it makes sense that it works. And yes, `%` style formatting is pretty old and you should use new style formatting – juanpa.arrivillaga Dec 20 '18 at 17:15
  • 1
    I am not sure what are you talking about when you say "old style" and "new style", but Python works in a way that, overriding certain method names, you can define the behaviour of some class' instances when they use certain operator. For example, when you create a class and add a method called `__mod__`, that method will define how the instances of the class will behave when operated with `%` operator. There is more information about this subject in [this question](https://stackoverflow.com/q/36442389/3692177) – SebasSBM Dec 20 '18 at 17:22
  • @SebasSBM Thank you, this link is clear on why `%=` works. For the [new style, old style](https://pyformat.info/) I am refering to [% vs str.format()](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format). – raratiru Dec 20 '18 at 17:26
  • @raratiru IMHO, `str.format` is a workaround, some kind of [wrapper function](https://en.m.wikipedia.org/wiki/Wrapper_function) to prevent some funny use cases of `%` operator with strings. The first answer of the question you linked shows a use-case with tuples (useful to parse multiple values at once into strings), where, to prevent TypeMismatch errors, you "hack" a single value as a 1-len tuple. The new `format` method probably wraps the original functionality to prevent this kind of cases right away, among other things, which helps to write cleaner code. And that's great. – SebasSBM Dec 20 '18 at 17:43
  • @SebasSBM I understand your point, it seemed strange that Django keeps -in this occasion only- the old formatting. Should it be because there is no equivalent of `%=` operator in the new formatting but at the same time this is not redundant, it is just old fashioned. – raratiru Dec 20 '18 at 18:03

1 Answers1

1

This is a feature of str (in both 2x and 3x). It shorthands message = message % params with message as format string. You can read up on similar operators like *= aka __imul__ here.

The string/modulus operator is for "old python formatting", which you can read about here along with the history of new and old.

raratiru
  • 8,748
  • 4
  • 73
  • 113
Nino Walker
  • 2,742
  • 22
  • 30