Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to prevent percent string substitution in python

>>> def mod2(n):
...   print 'the remainder is', n % 2
... 
>>> mod2(5)
the remainder is 1
>>> mod2(2)
the remainder is 0
>>> mod2('%d')
the remainder is 2
>>> mod2('%d\rHELLO. I AM A POTATO!')
HELLO. I AM A POTATO!

Is there anyway to disable % symbol (operator.mod) from doing wacky string substitution stuff? I always use str.format if I need anything like that, and would generally rather this string substitution feature didn't exist at all, giving a TypeError instead.

like image 873
wim Avatar asked Feb 19 '23 05:02

wim


1 Answers

You can't disable it with a switch, no. The str() type implements a __mod__ method to handle the formatting, it's not that Python special-cased the expression just for strings.

As such, to prevent this you either need to cast the n argument to something that is not a string (by converting it to int() for example), or subclass str() to override the __mod__ method:

>>> class noformattingstr(str):
...     def __mod__(self, other):
...         raise TypeError('String formatting using "%" has been deprecated')
... 
>>> noformattingstr('hello world: %d') % 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __mod__
TypeError: String formatting using "%" has been deprecated

You can assign this to __builtins__.str, but this does not mean that all string literals will then use your subclass. You'd have to explicitly cast your str() values to noformattingstr() instances instead.

like image 147
Martijn Pieters Avatar answered Feb 21 '23 01:02

Martijn Pieters