How to make a custom type "true" or not, in Python 1.5.2

Michael Hudson mwh21 at
Mon Feb 19 16:55:39 EST 2001

"Warren Postma" <embed at> writes:

> "Michael Hudson" <mwh21 at> wrote in message
> news:m3r90utl89.fsf at
> > "Warren Postma" <embed at> writes:
> >
> > You want nb_nonzero in the number methods struct, from memory...  and
> > the nb_nonzero field from the tp_as_number field from checking the
> > source (! where does my brain keep all these bits of information?).
> >
> Alas it appears you can't just fill this in. I looked at MxDateTime as a
> sample extension, and it says the first 10 items in the tp_as_number table
> must be non-null or python will crash, thus you have to write a little stub
> function. Kind of yucky. My objects have no possible numeric protocol.

Looking at Misc/HISTORY in the Python source implies that this hasn't
been the case since 1.5.2a1.  Do you need to support that far back?

> So I tried my earlier hunch about if len(x) is 0, even if the rest of the
> sequence protocol is undefined, it seems to work.  The weird thing here is
> that len(x) doesn't mean anything, other than I suppose, the object is an
> empty set if len(x) is zero.

I wouldn't be sure that this would work in the case that the
PyNumberMethods approach wouldn't.  I could extract 1.5.1 from cvs, I
suppose, but I'm not going to.  Actually, I just did, and I think

<your object> + 1

would probably crash (I think Python would try to call sq_concat
without checking it).

> That seemed to work.  Has anyone got any opinion on the Relative
> Goodness or Badness of using Len(x) => 0 to impute Non-Thingy-ness
> upon some thing, when implementing the whole tp_as_number protocol
> is not the Right Thing to Do?

Well, it too is a bit yucky.  If you can get away with demanding
1.5.2, go for the number methods.


42. You can measure a programmer's perspective by noting his 
    attitude on the continuing vitality of FORTRAN.
  -- Alan Perlis,

More information about the Python-list mailing list