[Python-Dev] [2.3a2+] Change in int() behavior
David Abrahams
dave@boost-consulting.com
Sat, 08 Mar 2003 02:27:26 -0500
Tim Peters <tim.one@comcast.net> writes:
> [David Abrahams]
>> Yes, but in the meantime, PyInt_AS_LONG( invoke_int_conversion(x) )
>> might be a crash instead of raising an exception.
>
> As the comment before that macro's definition says,
>
> /* Macro, trading safety for speed */
>
> PyInt_AsLong() won't crash, but its result needs to be checked for an error
> return.
>
> Note that your example:
>
> PyInt_AS_LONG( invoke_int_conversion(x) )
>
> wasn't safe before either: I'm not sure what invoke_int_conversion(x) means
> exactly, but the plausible meanings I can think of for it *could* yield a
> NULL pointer, or a pointer to a non-int object, in any version of
> Python
Yeah, actually invoke_int_conversion basically invoked the nb_int
slot, and I _was_ doing the NULL check (don't forget, C++ has
exceptions).
> (e.g., PyNumber_Int() calls tp_as_number->nb_int but doesn't check the
> return value for sanity). In either of those cases PyInt_AS_LONG blindly
> applied to the result could crash.
>
>
>> That's what is causing my test to fail. I guess I just need to lowercase
>> a few characters,
>
> You also need to check for an error return -- PyInt_AsLong() can fail.
I knew that, but thanks. I was exaggerating for effect; did it, it
works.
>> but it's worth noting that this change breaks existing
>> extension module code.
>
> I'm not sure it can break any I wouldn't have considered broken before.
> It's normal (& expected) not to use the macro unless you *know* you've got
> an int object, usually by virtue of passing a PyInt_Check() test first.
I guess I was reading
http://www.python.org/doc/current/ref/numeric-types.html#l2h-184 a
little too strongly when I wrote the code:
__complex__(self)
__int__(self)
__long__(self)
__float__(self)
Called to implement the built-in functions complex() int() long()
and float(). Should return a value of the appropriate type.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
That's pretty weak language, and even if it were strong I should've
known better. Some joker would eventually add an __int__ method,
that returns, say, a Long. I just didn't expect it to happen in the
core (for some reason).
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com