簡體   English   中英

在裝飾器中獲取 Python 函數參數的名稱

[英]Get the names of a Python function’s parameters when it is inside a decorator

我想在裝飾器函數中獲取函數的參數名稱,我一直在獲取裝飾器內部的函數包裝參數,而不是原始方法的參數

_component_name_does_not_exist_error 是裝飾器, create_queue_to_component 是方法,我想至少獲得名稱 component_name 和 queue_name

def _component_name_does_not_exist_error(func):
    def function_wrapper(self, component_name):
        if not self._does_component_exist(component_name):
            return self._create_response(
                False,
                f"Component named {component_name} doesn't exist"
            )
        return func

    return function_wrapper

@_component_name_does_not_exist_error
def create_queue_to_component(self, component_name,
                              queue_name, queue_size=1):
    if self.components[component_name].does_queue_exist(queue_name):
        return self._create_response(
            False,
            f"Queue named {queue_name} already exist"
        )

    self.components[component_name].create_queue(queue_name=queue_name,
                                                 queue_size=queue_size)
    return self._create_response(
        True,
        f"The Queue {queue_name} has been created"
    )

我嘗試使用這些方法但沒有運氣,所有返回 component_name 沒有 queue_name (為了使下面的代碼更清晰,pipeline_manager 是包含這些方法的類的對象)

def get_method_parameters(self):
    print(inspect.signature(self.pipeline_manager.create_queue_to_component))
    print(self.pipeline_manager.create_queue_to_component.__code__.co_varnames)
    print(inspect.getfullargspec(self.pipeline_manager.create_queue_to_component))

感謝您閱讀本文並提供幫助:)

使用functools.wrapsfunctools模塊

import functools

def _component_name_does_not_exist_error(func):
    @functools.wraps(func)
    def function_wrapper(self, component_name):
        if not self._does_component_exist(component_name):
            return self._create_response(
                False,
                f"Component named {component_name} doesn't exist"
            )
        return func

    return function_wrapper

然后

print(inspect.signature(self.pipeline_manager.create_queue_to_component))

給你我認為你想要的,這是create_queue_to_component函數的參數名稱。

這個答案很好地描述了functools.wraps

def _component_name_does_not_exist_error(func):
    @functools.wraps(func)
    def function_wrapper(self, *args, **kwargs):
        if not self._does_component_exist(kwargs['component_name']):
            return self._create_response(
                False,
                f"Component named {kwargs['component_name']} doesn't exist"
            )
        return func(self, *args, **kwargs)

    return function_wrapper

這對我有用(感謝@wstk 提出您的答案並幫助我找到答案)

暫無
暫無

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

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