如何从Cython方法描述符中获取参数名称和__annotations__?

时间:2016-08-31 07:26:57

标签: python methods annotations cython inspect

如果我在cdef class中定义方法,则方法没有关于参数和注释的任何信息:

Python类:

class MyClass:
   def test(self, arg: int):
      pass
print(dir(MyClass.test))

['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

Cython课程:

cdef class MyClass:
   def test(self, arg: int):
      pass
print(dir(MyClass.test))
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

有没有办法从Cython方法获取带有注释的argumnets?

P.S。 Cython类方法的类型不是方法:<class 'method_descriptor'>,而不是<class 'cython_function_or_method'>

1 个答案:

答案 0 :(得分:2)

根据Cython github repo上的this issue,添加了注释,但仅适用于cdef函数:

%%cython
def test2(arg: int): pass
cpdef test1(arg: int): pass
cdef test(arg: int): pass

print(['__annotations__' in dir(i) for i in [test2, test1, test]])
[False, False, True]

除此之外,获取__annotations__只会返回一个空字典。似乎注释仅在生成C代码(尚未验证)时使用,并且不适合用户使用。