繁体   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