python - 在装饰器中获取 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))
感谢您阅读本文并提供帮助:)
解决方案
functools.wraps
从functools
模块使用
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
得很好。
推荐阅读
- excel - 将用户窗体输入传输到单元格范围
- moodle-api - 如何在 Moodle Web 服务上获取注册用户的角色 ID
- cordova - PhoneGap - Android 视口被忽略(我知道,我知道)
- python - 在 Python 中,如何统计 MongoDB 中包含特定状态的所有文档?
- meteor - 在 Iron-router Meteor 中覆盖布局模板
- angular - 我的自定义“filteritemTemplate”不起作用?
- android - Facebook 广告不是通过 Android 中的 Google DFP 中介投放的吗?
- java - AuthenticationProcessingFilter 和 WebSecurityConfigurerAdapter 导致循环依赖
- angular - 在 mat-calendar 中突出显示日期
- regex - “null”字符串和空字符串的 Json Schema 验证