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?

5
  • 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 Commented Dec 20, 2018 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 Commented Dec 20, 2018 at 17:22
  • @SebasSBM Thank you, this link is clear on why %= works. For the new style, old style I am refering to % vs str.format(). Commented Dec 20, 2018 at 17:26
  • @raratiru IMHO, str.format is a workaround, some kind of 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. Commented Dec 20, 2018 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. Commented Dec 20, 2018 at 18:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.