[英]Cython - Checking types of objects
How can I check the types of python objects within cython? 如何检查cython中的python对象类型?
My Cython extension E
compiles to E.pyd
within a module M
. 我的Cython扩展名
E
在模块M
编译为E.pyd
。
I am trying to check the type of a python parameter in class A
of Cython extension E
. 我正在尝试检查Cython扩展
E
class A
中的python参数类型。
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, 问题是当我去使用python的扩展名时,
from M import E
a = A()
b = A()
a.foo(b)
bar is not A, but rather MEA
when I use type(b)
from Python 当我使用Python中的
type(b)
时,bar不是A,而是MEA
I have tried if bar is MEA:
from within Cython but the compiler complains undeclared name not builtin: M
, since Cython doesn't know about the module. 我已经尝试过
if bar is MEA:
从Cython内部,但是编译器抱怨undeclared name not builtin: M
,因为Cython不知道该模块。
In Cython as in Python is
is the object identity. 在Cython中,就像在Python
is
是对象标识。 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 如果要检查
bar
是否为A
类型或其任何子类型
or 要么
if type(bar) is A: ...
If you want to check is bar
is exactly of type A
. 如果要检查的是
bar
恰好是A
类型。
Alternatively Cython
provide type checking via: Cython
可以通过以下方式提供类型检查:
def foo(self, A bar):
which allows the user to pass also None
meaning no object. 这允许用户也传递
None
表示没有对象。 If you want to exclude None
write: 如果要排除
None
写:
def foo(self, A bar not None):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.