簡體   English   中英

從FrameInfo或python中的frame獲取函數簽名

[英]get function signature from FrameInfo or frame in python

在python中編寫自己的異常鈎子時,我想到了使用inspect -module來向自己提供有關如何調用該函數的更多信息。

這意味着函數的簽名以及傳遞給它的參數

import inspect

frame_infos = inspect.trace() # get the FrameInfos

for f_idx, f_info in enumerate(frame_infos):
    frame_dict.update(f_info.frame.f_locals) # update namespace with deeper frame levels
    #Output basic Error-Information
    print(f'  File "{f_info.filename}", line {f_info.lineno}, in {f_info.function}')
    for line in f_info.code_context:
        print(f'    {line.strip()}')

    ########################################################
    # show signature and arguments 1 level deeper
    if f_idx+1 < len(frame_infos): 
        func_name = frame_infos[f_idx+1].function #name of the function
        try:
            func_ref = frame_dict[func_name] # look up in namespace
            sig = inspect.signature(func_ref) # call signature for function_reference
        except KeyError: sig = '(signature unknown)'
        print(f'    {func_name} {sig}\n')
        print(f'    {frame_infos[f_idx+1].frame.f_locals}\n')

像這樣的基本示例可以很好地工作:

def test1 ( x: int, y: tuple = 0 )->list: # the types obviously dont match
    return test2(y, b=x, help=0)

def test2 ( a, *args, b, **kwargs ):
    return a + b / 0

try: 
    test1(5) 
except: ...

輸出:

File "C:/test/errorHandler.py", line 136, in <module>
    test1(5)
    test1 (x:int, y:tuple=0) -> list
    {'y': 0, 'x': 5}
File "C:/test/errorHandler.py", line 130, in test1
    return test2(y, b=x, help=0)
    test2 (a, *args, b, **kwargs)
    {'kwargs': {'help': 0}, 'args': (), 'b': 5, 'a': 0}
File "C:/test/errorHandler.py", line 133, in test2
    return a + b / 0

但是,一旦您離開1個文件,就無法將函數名稱映射到基本名稱空間。

file1: import file2; try: file2.foo() except: ...文件2 import file2; try: file2.foo() except: ... import file2; try: file2.foo() except: ...
file2: import file3; def foo(): file3.foo() import file3; def foo(): file3.foo()
file3: def foo(): return 0/0

因此,從FrameInfo ,我正在尋找一種從FrameInfoframe FrameInfo獲取函數的方法(例如<function foo at 0x000002F4A43ACD08> ),但是我看到的唯一信息是名稱,文件和行。
(我不喜歡通過在特定行中查看源文件來獲得簽名的想法。)

到目前為止,最好的參考是Inspect -documentation ,但是我還沒有找到有用的東西。

基於jsbueno的 回答 ,我找到了恢復簽名的解決方案。

使用gc (垃圾收集器)函數get_referrers()可以搜索直接引用特定對象的所有對象。

通過框架的f_code提供的代碼對象,您可以使用此函數查找框架以及該函數。

code_obj = frame.f_code
import gc #garbage collector
print(gc.get_referrers(code_obj))
# [<function foo at 0x0000020F758F4EA0>, <frame object at 0x0000020F75618CF8>]

因此,只需找到真正的功能就可以了:

# find the object that has __code__ and is actally the object with that specific code    
[obj for obj in garbage_collector.get_referrers(code_obj)
 if hasattr(obj, '__code__')
 and obj.__code__ is code_obj][0]

現在您可以在過濾對象上使用inspect.signature()


來自gc.get_referrers(objs) objs)的gc.get_referrers(objs)

此功能將僅定位那些支持垃圾收集的容器; 找不到引用其他對象但不支持垃圾回收的擴展類型。


完整的代碼示例:

import inspect
import gc

def ERROR_Printer_Inspection ( stream = sys.stderr ) :
    """
    called in try: except: <here>
    prints the last error-traceback in the given "stream"
    includes signature and function arguments if possible
    """
    stream.write('Traceback (most recent call last):\n')
    etype, value, _ = sys.exc_info() # get type and value for last line of output
    frame_infos = inspect.trace() # get frames for source-lines and arguments

    for f_idx, f_info in enumerate(frame_infos):
        stream.write(f'  File "{f_info.filename}", line {f_info.lineno}, in {f_info.function}\n')
        for line in f_info.code_context: # print location and code parts
            stream.write(f'    {line.lstrip()}')

        if f_idx+1 < len(frame_infos): # signature and arguments
            code_obj = frame_infos[f_idx+1].frame.f_code # codeobject from next frame
            function_obj = [obj for obj in gc.get_referrers(code_obj) if hasattr(obj, '__code__') and obj.__code__ is code_obj]

            if function_obj: # found some matching object
                function_obj=function_obj[0] # function_object
                func_name = frame_infos[f_idx + 1].function # name 
                stream.write(f'    > {func_name} {inspect.signature(function_obj)}\n')

            next_frame_locals = frame_infos[f_idx+1].frame.f_locals # calling arguments
            # filter them to the "calling"-arguments
            arguments = dict((key, next_frame_locals[key]) for key in code_obj.co_varnames if key in next_frame_locals.keys())
            stream.write(f'    -> {str(arguments)[1:-1]}\n')

    stream.write(f'{etype.__name__}: {value}\n')
    stream.flush()

問題:

如果在函數啟動后對其進行編輯,則顯示“調用”參數可能會誤導用戶:

def foo (a, b, **kwargs):
    del a, kwargs
    b = 'fail'
    return 0/0

try: foo(0, 1, test=True)
except: ERROR_Printer_Inspection()

輸出:

Traceback (most recent call last):
  File "C:/test/errorHandler.py", line 142, in <module>
    try: foo(0, 1, test=True)
    > foo (a, b, **kwargs)
    -> 'b': 'fail'
  File "C:/test/errorHandler.py", line 140, in foo
    return 0 / 0
ZeroDivisionError: division by zero

您無法相信,但這是另一個問題。


鏈接:

如果您想自己研究,請點擊以下鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM