Bug or feature?

Alexey Nezhdanov snake at penza-gsm.ru
Thu Jan 15 02:07:39 EST 2004


> Alexey Nezhdanov wrote:
> > Hello. Found a strange python behaivoir while writing some
> > object. I've
> > stripped out all other stuff so the problem is stright here:
> > =================================
> > #!/usr/bin/python
> >
> > class Object:
> >      def __init__(self,val):
> >          self.val=val
> >
> >      def Sub(self,delta):
> >          self.val-=delta
> >          return delta
> >
> > c=Object(1)
> >
> > ### case 1 ###
> > d=c.Sub(1)
> > c.val+=d
> > print 'case A:',c.val
> >
> > ### case 2 ###
> > c.val+=c.Sub(1)
> > print 'case B:',c.val
> > =================================
> > Case 1 and case 2 prints out different calues (1 and 2 respectively).
> > Do not know - if this is a bug or feature of python.
>
> Disassembly is your friend:
> ...
> As you can see, the order of evaluation in pluseq() is:
>    load val, call Sub(), add, store result.
> whereas the order in subthenplus() is:
>    call Sub(), load val, add, store result.
>
> ...which explains things a bit. If we had written inst.val = inst.val +
> inst.Sub(1), the order would be the same as pluseq (but we'd get a
> binary add instead of inplace).
> Robert Brewer
Ok. Let me explain. I know the reasons of this particular effect. I have not 
disassembled code myself but nevertheless I come to the same idea myself.
The question is - is such *python* behaivoir is correct or not.

Since one person can write string like
c.val+=c.Sub(1)
he can expect that both addition and Sub execution will complete and no 
results will be dropped.

-- 
Respectfully
Alexey Nezhdanov







More information about the Python-list mailing list