Entry
Incrementing integers (was: Python complaints)
Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 336, Michael Hudson
"""
Packages: miscellaneous.sick_and_twisted
"""
"""
> > I find myself grumbling about having to type "x = x + 1". The really
> > clean thing to do, given that integers are objects, would be to define
> > increment and decrement methods, so you'd type something like "i.incr()".
>
> > Wouldn't this be impossible, since Integers are also immutable? So, eg,
> > i.incr() could only return an incremented version of i, but not actually
> > increment i?
>
> Right, this is what Gordon was pointing out. A "++" method could not
> magically reach out of its object, find the "i" variable, and bind it
> to the incremented value.
Hate to be awkward, but when it comes to things like this, there's
very little like this that can't be done in Python!
"""
def incr(var):
try:
raise 1/0
except ZeroDivisionError:
import sys,dis
f = sys.exc_traceback.tb_frame.f_back
loadins = f.f_code.co_code[f.f_lasti - 3:f.f_lasti]
loadop = ord(loadins[0])
name = dis.opname[loadop]
loadarg = ord(loadins[1]) + 256*ord(loadins[2])
vname = f.f_code.co_names[loadarg]
f.f_locals[vname] = f.f_locals[vname] + 1
x=1
incr(x)
print x
# 2
"""
well, it works in the IDLE shell window...
I'll stop now ;-).
> Something like this could be accomplished by tinkering with Python's
> parser, but that wouldn't be a great idea.
As above, not necessary.
> A lot of work for something that would never find wide acceptance.
That much is true!
"""