【发布时间】:2021-08-21 01:32:51
【问题描述】:
这是我现在正在工作的更大代码的玩具示例。假设我有一个函数,并且我想以一种可以记录有效、遗留或禁止的参数的方式来装饰它:
@option("1")
@option("2", legacy=True)
def do_stuff(opt):
print(f"You chose {opt}!")
do_stuff("1")
do_stuff("2")
do_stuff("3")
这样的结果会是这样的
You chose 1!
2 is deprecated!
You chose 2!
3 is not allowed!
我现在尝试用一些不同的方式来实现这种行为,我最近的尝试是这样的:
from functools import wraps
def option(opt, legacy=False):
def add_opt(f, option):
if not hasattr(f, "opts"):
f.opts = []
f.opts.append(option)
def add_legacy_opt(f, option):
if not hasattr(f, "legacy"):
f.legacy = []
f.legacy.append(option)
def decorate(func):
@wraps(func)
def wrapper(option):
if hasattr(wrapper, "opts") and option not in wrapper.opts:
print(f"{option} is not allowed!")
return
if hasattr(wrapper, "legacy") and option in wrapper.legacy:
print(f"{option} is deprecated!")
return func(option)
add_opt(wrapper, opt)
if legacy:
add_legacy_opt(wrapper, opt)
return wrapper
return decorate
它几乎有效。问题是它给了我双重遗留信息:
You chose 1!
2 is deprecated!
2 is deprecated!
You chose 2!
3 is not allowed!
如果有人有任何想法,请告诉我!谢谢:D
更新:以不同的顺序进行装饰:
@option("2", legacy=True)
@option("1")
def do_stuff(opt):
print(f"You chose {opt}!")
【问题讨论】:
标签: python metaprogramming python-decorators