gpt4 book ai didi

python - 获取函数的局部变量

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:45 24 4
gpt4 key购买 nike

我正在尝试从装饰器中获取局部变量。一个例子:

def needs_privilege(privilege, project=None):
"""Check whether the logged-in user is authorised based on the
given privilege

@type privilege: Privilege object, id, or str
@param privilege: The requested privilege"""

def validate(func, self, *args, **kwargs):
"""Validator of needs_privillige"""
try: check(self.user, privilege, project)
except AccessDenied:
return abort(status_code=401)
else:
return func(self, *args, **kwargs)

return decorator(validate)

装饰函数后,像这样:

 @needs_privilege("some_privilege")
def some_function():
pass

我想从 some_function 中检索“特权”变量(validate() 使用)。搜索了一个多小时后,我感到很迷茫。这可能吗?

编辑:让我更彻底地描述一下我的问题:我可以在不执行some_function 的情况下获取字符串“some_prvilege”吗?像这样的东西:

a = getattr(module, 'somefunction')
print a.decorator_arguments

?感谢您到目前为止对我的帮助!

最佳答案

你的装饰器基本上检查用户是否有执行给定功能的权限,我实际上不明白你为什么要检索(附加)被包装的功能的权限,但你可以在不添加的情况下执行此操作所有函数的另一个参数。

def needs_privilege(privilege, project=None):
"""Check whether the logged-in user is authorised based on the
given privilege

@type privilege: Privilege object, id, or str
@param privilege: The requested privilege"""

def validate(func, self, *args, **kwargs):
"""Validator of needs_privillige"""
try: check(self.user, privilege, project)
except AccessDenied:
return abort(status_code=401)
else:
return func(self, *args, **kwargs)
validate.privelege = privelege
return decorator(validate)

顺便说一句,你的装饰器应该是这样的:

def needs_privilege(privilege, project=None):
def validate(func):
def new_func(self, *args, **kwargs):
try:
check(self.user, privilege, project)
except AccessDenied:
return abort(status_code=401)
else:
return func(self, *args, **kwargs)
new_func.privilege = privilege
return new_func
return validate

关于python - 获取函数的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com