Simd
Simd

Reputation: 21343

Why don't you get a type error when you pass a float instead of an int in cython

I have a cython function:

def test(int a, int b):
    return a+b

If I call it with:

test(0.5, 1)

I get the value 1.

Why doesn't it give a type error?

Upvotes: 1

Views: 86

Answers (1)

ead
ead

Reputation: 34367

This is because float defines the special function __int__, which is called by Cython along the way (or more precise PyNumber_Long, at least this is my guess, because it is not easy to track the call through all these defines and ifdefs).

That is the deal: If your object defines __int__ so it can be used as an integer by Cython. Using Cython for implicit type-checking is not very robust.

If you want, you can check, whether the input is an int-object like in the following example (for Python3, for Python2 it is a little bit more complex, because there are different int-classes):

%%cython
from cpython cimport PyLong_Check
def print_me(i):
    if not PyLong_Check(i):
        print("Not an integer!")
    else:
        print(i)

Upvotes: 1

Related Questions