如何从Cython方法描述符获取参数名和注释?

2024-04-18 23:17:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在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']

赛顿班:

^{pr2}$

有什么方法可以从Cython方法中获得带注释的argumnet吗?在

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


Tags: 方法nametestselfreducedocdirmyclass
1条回答
网友
1楼 · 发布于 2024-04-18 23:17:48

根据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代码(尚未验证)时使用,并不意味着对用户可用。在

相关问题 更多 >