[capi-sig] Checking int type

Vojtěch Rylko vojta.rylko at seznam.cz
Mon May 24 13:31:04 CEST 2010


But after unpacking, I still cannot detect no-integer type object.

 >>> from primes import is_prime
 >>> is_prime(7)
True
 >>> is_prime(5.5) # should raise exception, but is rounded as 5
__main__:1: DeprecationWarning: integer argument expected, got float
True
 >>> is_prime(9.8) # should raise exception, but is rounded as 9
False

=================================
static PyObject *is_prime(PyObject *self, PyObject *arg)
{
     PyObject *value;
     if (!PyArg_ParseTuple(arg, "O", value))
         return NULL;

     if (PyInt_Check(value)) {
         // never raise (test case - in real its if(!PyInt_Check(value) 
which always raise)
         PyErr_SetString(PyExc_ValueError, "only integers are acceptable");
         return NULL;
     }
     int number;
     if (!PyArg_ParseTuple(value, "i", &number))
        return NULL;

     int result = is_prime_solve(number);


Dne 24.5.2010 8:56, Jon Parise napsal(a):
> On Sun, May 23, 2010 at 7:40 AM, Vojtěch Rylko<vojta.rylko at seznam.cz>  wrote:
>
>    
>> what am I doing wrong?
>>
>> C code:
>> --------------
>> static PyObject *is_prime(PyObject *self, PyObject *value)
>> {
>>     if (!PyInt_Check(value)) {
>>         PyErr_SetString(PyExc_TypeError, "only integers are acceptable");
>>         return NULL;
>>     }
>> --------------
>>
>> Test (I'm using integer 3):
>> ------------
>>      
>>>>> primes.is_prime(3)
>>>>>            
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in<module>
>> ValueError: only integers are acceptable
>> -------------
>>      
> The second argument ('value', in your code) is actually a tuple
> containing the arguments passed to your is_prime() function.  You'll
> need to unpack the individual values from that tuple.
>
> http://docs.python.org/extending/extending.html#extracting-parameters-in-extension-functions
>
>    



More information about the capi-sig mailing list