1

我目前正在从事一个项目,我无法发布破坏代码,即函数名称必须保持不变,同样适用于其参数和代码中的所有其他内容。话虽如此,人们通常将位置参数作为关键字参数调用函数,例如

def foo(a):
    ...
foo(a=2)

问题是我必须更改参数名称,并且在使用位置参数调用函数时可能会破坏代码,因为它本来是:

def foo(a, b, c=3, d=5):
    ...
foo(3,4) # works
foo(a=3,b=4) # works

# After renaming 'a'
def foo(ax, b, c=3, d=5):
    ...
foo(3,4) #works
foo(a=3, b=4) # doesn't work

我尝试添加 **kwargs,但是,它并不能解决所有问题

def foo(b, ax=None, c=3, d=5, **kwargs):
    if 'a' in kwargs:
        warn('\'a\' is deprecated, use \'ax\' instead')
        ax = kwargs['a']
    assert ax is not None, "ax cannot be None"
    ...
foo(a=3, b=4) # works
foo(ax=3, b=4) # works
foo(3,4) #doesn't work

有谁知道我该如何解决这个问题?

4

0 回答 0