Magic methods in extension types

Michael Hudson mwh at python.net
Tue Apr 27 04:50:52 EDT 2004


Jacek Generowicz <jacek.generowicz at cern.ch> writes:

> Michael Hudson <mwh at python.net> writes:
> 
> > Jacek Generowicz <jacek.generowicz at cern.ch> writes:
> > 
> > > Michael Hudson <mwh at python.net> writes:
> > > 
> > > > Not finding the tp_as_number->nb_inplace_add field?
> > > 
> > > ( ... or tp_as_sequence ... )
> > > 
> > > I was afraid you (someone) was going to say that.
> > 
> > Why?
> 
> Because I'm too lazy to pollute my tiny extension type with a whole
> thingy_as_number sturucture for the sake of just one maginc method :-)

If __iadd__ is the *only* magic method you're adding, you deserve to
lose...

> > Well, the type of old-style classes has something in it's
> > tp_as_number->nb_inplace_add slot that looks in the class dictionary
> > for an __iadd__ method.
> > 
> > If you'd made that a new-style class, you would be surprised!
> 
> Don't follow ... you mean if I had done this:
> 
>     >>> class foo(object):
>     ...     def __iadd__(self,other):
>     ...         print "__iadd__ running"
>     ...         return self
>     ... 
>     >>> f = foo()
>     >>> f += 2
>     __iadd__ running
> 
> ?

Yup: you've added something to a type object, something you'd said
you'd be surprised to hear.

> > > Python manages to map "+=" to the method called "__iadd__" in
> > > user-defined classes, but not for extension types. What is the
> > > essential difference that makes that mapping work in one case but
> > > not in the other?
> > 
> > Well, for old-style classes a whole bunch of code like:

[...]

> > and for new-style classes much hair in typeobject.c:type_new and
> > therein called functions.  Extension types don't go through type_new
> > and are expected to go the other way round, in a sense: define
> > something in tp_as_number->nb_inplace_add and a wrapper called
> > __iadd__ will be created for you.
> 
> Yuk.

Why?

> You are, in summary, saying that by _far_ the simplest way of adding
> __iadd__ to an extenion type is via tp_as_number->nb_inplace_add,
> aren't you.

Yes.  I'm surprised at your apparent surprise, but then I've had my
head in the guts of Python's implementation for quite some time
now... implementing types in C is really quite different from
implementing them in Python, something which has only become
surprising since 2.2...

Cheers,
mwh

-- 
  Gullible editorial staff continues to post links to any and all
  articles that vaguely criticize Linux in any way.
         -- Reason #4 for quitting slashdot today, from
            http://www.cs.washington.edu/homes/klee/misc/slashdot.html



More information about the Python-list mailing list