首页 > 解决方案 > 我可以在调用函数之前修补函数参数/变量吗?

问题描述

我有一个第三方软件包可以做到这一点:

def build(debug=False):
    args = []
    if not (debug):
        args.append('--windowed')
    args.extend(['--icon', path('src/main/icons/Icon.ico')])
    # and much, much more

我希望猴子修补这个功能成为:

def build(debug=False, args=[]):
    # remove the line: args = []
    # and retain the rest of the function

我知道我可以例如执行以下操作:

def monkeypatched_build(debug=False, args=[]):
    # remove the line: args = []
    # and include all of the other code here

build = monkeypatched_build

但是,build在我的例子中,函数很复杂,如果可能的话,我想避免维护这个函数的单独版本,而只是改变我可以修改args变量的方式。

我不确定这是可能的,因为我需要在调用之前修改函数。有任何想法吗?

标签: python

解决方案


对于不涉及此 hack 的潜在解决方案,您是否可以修改构建功能?如果是这样,您可以添加一个默认为 true 的标志参数。

def build(debug=False, overwrite_flag = True, args = []):
    if overwrite_flag:
        args = []
    #rest of the function

但是,您要问的实际上是抑制函数中编写的指令之一,而不仅仅是添加新参数。可以使用装饰器管理新参数,但是我不知道是否会否决函数的指令。


推荐阅读