简体   繁体   English

Cython-检查对象类型

[英]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):

See Cython docs on extension types 请参阅有关扩展类型的Cython文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM