试一试.Catch宏包装器在cython中的等效

try..catch macro wrapper equivalent in cython

本文关键字:cython Catch 包装 试一试      更新时间:2023-10-16

我正在包装大量c++函数,如果底层套接字连接丢失,这些函数可能会引发异常。虽然我已经弄清楚如何包装我的"get connection"函数来重新建立连接和/或尝试列表中的其他可用服务器,但我无法找出创建一个try..的解决方案,除了包装器提供给80+ c++函数。

#-- client.pxd ---
cdef extern from "rpc/RpcService.h": 
    cdef cppclass RpcServiceClient:
        void getProject(ProjectT&, Guid& id) nogil except +
cdef extern from "client.h":
    cdef cppclass Client:
        RpcServiceClient proxy() nogil 
    cdef Client* getClient() nogil except +

#-- module.pxd ---
cdef inline Client* conn() except *:
   # wrap getClient() here with try..except if the 
   # connection was never established
cpdef inline get_project(Guid& guid):
    cdef: 
        ProjectT projT  # cpp object
        Project project # cdef python class
    # this would catch fine in my conn() wrapper
    # if the connection had never been established
    # the first time. But if the existing connection
    # suddenly drops, it will be getProject() that
    # raises the exception
    conn().proxy().getProject(projT, guid)
    project = initProject(projT)
    return project

关于如何将所有这些c++函数包装在像try_call()这样的东西中,有什么建议吗?如果这是纯python,我可以简单地这样做:

def try_call(fn, *args, **kwargs):
    # try fn(*args, **kwargs) and handle
try_call(conn().proxy().getProject, projT, guid)

但是显然我不能将这些python函数作为python对象传递(或者我可以?)

或者在c++中像这样:

TRY_CALL_OR_RECONNECT
conn().proxy().getProject(projT, guid)
END_TRY_CALL_OR_RECONNECT

你可能想查看一下decorators

def try_wrapper(x):
    try:
        x()
    except:
        doSomethingElse()
@try_wrapper
def defYouWantToWrap():
    doSomething()

这可能不是最好的教程,但希望它能给你指明正确的方向