Python complaints
Jesse D. Sightler
jsight at mindspring.com
Tue Nov 30 21:14:58 EST 1999
Michael Hudson wrote:
>
> wware-nospam at world.std.com (Will Ware) writes:
>
> > Will Ware wrote:
> > > 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()".
> >
> > Jesse D. Sightler (jsight at mindspring.com) wrote:
> > > 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)
> >>> x
> 2
Ack, and I though Perl was the only language that made you do stuff like
that. :) Could you please explain this little piece of code?
It sure looks like byte-code dependant, self-modifying crazyness to me.
:)
---------------
Jesse D. Sightler
http://www.biddin.com/delorean/
More information about the Python-list
mailing list