首页 > 解决方案 > 在装饰器中获取 Python 函数参数的名称

问题描述

我想在装饰器函数中获取函数的参数名称,我不断获取装饰器内部的函数包装器参数,而不是原始方法的参数

_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"
    )

我尝试使用这些方法没有运气,都返回没有 queue_name 的 component_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))

感谢您阅读本文并提供帮助:)

标签: pythonpython-3.xdynamicpython-decorators

解决方案


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得很好。


推荐阅读