我正在写一个递归函数,它看起来像这样:
def mah_recursive_function(some_arg, some_option=True):
if some_thing:
some_arg.doFancyStuff();
mah_recursive_function(some_arg,
some_option=some_option
)
elif some_thing:
some_arg.doOtherFancyStuff();
mah_recursive_function(some_arg,
some_option=some_option
)
很明显,那些some_option=some_option
赋值确实是多余的,而且,由于我有多个永久性的kwarg选项,这些多余的赋值变得非常烦人。你知道吗
from functools.magical_stuff import get_current_kwargs
mah_recursive_function(
some_arg, **get_current_kwargs()
)
我不想用多余的行来填充我的递归调用。最好的办法是什么?你知道吗
下面是一个我认为您希望通过递归实现的最小示例—通常每次都使用相同的值,但可以灵活地更改其中的一些值。这是你想要的吗?你知道吗
关键的一点是获取args/kwargs的副本,否则您将在任何时候更改某些内容时为每个未完成的调用修改args/kwargs。你知道吗
你可以用一个自动提供原件和复印件的装饰器来装饰它,也许甚至不必分出当前的名字。你知道吗
结果:
考虑使用包装函数以避免重复:
您的选项将自动传播(作为局部变量)到内部函数,该函数可以像往常一样递归,而不必重复
option=
参数。你知道吗相关问题 更多 >
编程相关推荐