How can I check the types of python objects within cython?
My Cython extension E compiles to E.pyd within a module M.
I am trying to check the type of a python parameter in class A of Cython extension E.
cdef class A:
def foo(self, bar):
if bar is A:
print("ok")
else
print("invalid")
The trouble is when I go and use the extension from python,
from M import E
a = A()
b = A()
a.foo(b)
bar is not A, but rather M.E.A when I use type(b) from Python
I have tried if bar is M.E.A: from within Cython but the compiler complains undeclared name not builtin: M, since Cython doesn't know about the module.
In Cython as in Python is is the object identity. It is not used for checking type.
You should write:
if isinstance(bar, A):
...
if you want to check if bar is of type A or any of its subtype
or
if type(bar) is A:
...
If you want to check is bar is exactly of type A.
Alternatively Cython provide type checking via:
def foo(self, A bar):
which allows the user to pass also None meaning no object. If you want to exclude None write:
def foo(self, A bar not None):
See Cython docs on extension types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With