misleading prefix ++

Peter Otten __peter__ at web.de
Sat May 20 09:13:42 EDT 2006


LuciferLeo at gmail.com wrote:

> but when I input:
>>>> ++i
> and the interpreter replies
> 0
> 
> Don't you think it is misleading when you expect a variable to
> increment?

You have been warned...

$ cat pp.py
i = 42
++i
print i
--i
$ pychecker pp.py
Processing pp...
42

Warnings...

pp.py:2: Operator (++) doesn't exist, statement has no effect
pp.py:4: Operator (--) doesn't exist, statement has no effect

...or you would have been, had you used the pychecker :-)

Now I'm not recommending

>>> class Int(object):
...     def __init__(self, value=0):
...             self.value = 0
...             self.half = False
...     def __pos__(self):
...             if self.half:
...                     self.value += 1
...             self.half = not self.half
...             return self
...     def __str__(self):
...             return str(self.value)
...     __repr__ = __str__
...
>>> i = Int()
>>> i
0
>>> ++i
1
>>> ++i
2
>>> i
2

which is slightly harder to fix than to break but gives some (weak)
motivation not to rule out multiple prefixed signs.

Peter



More information about the Python-list mailing list