我可以在调用函数之前先对函数的参数/变量进行修改吗?

时间:2018-11-26 09:04:48

标签: python

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

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变量的方式

我不确定这是否可行,因为我需要在调用该函数之前对其进行修改。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

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

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