如何找出在python中传递的两个参数?

时间:2017-03-15 05:46:54

标签: python

假设我们要在函数中添加对新参数名称的支持,而不删除旧参数名称(而是为此添加弃用警告)

def f(a=2, b=2):
    # we want users to use b, so need to pass deprecation 
    # warning for a when a is used.
    if(b is 2 and a is not 2): # a is used
        warnings.warn("a is deprecated in future update. Please use b")
        # But we miss case when a=2 is passed

请建议使用此功能的更好方法。谢谢:))

3 个答案:

答案 0 :(得分:1)

使用None作为a的默认值。如果None是用户可能传入的有效值,请使用只有您有权访问的唯一对象:

missing = object()

def f(a=missing, b=2):
    if a is not missing:
        # etc.

一般来说,这段代码有气味......可能有更好的方法来设计你的API,这样你就不会有这个问题。

答案 1 :(得分:1)

制作a = None

def f(a=None, b=None):
    if a is not None:
        warnings.warn("a is deprecated in future update. Please use b")

顺便说一句,python2有一个内置的http://ww1.microchip.com/downloads/en/DeviceDoc/60001120F.pdf和一个DeprecationWarning。检查一下。

def f(a=None, b=None):
    if a is not None:
        raise PendingDeprecationWarning('a is deprecated in future update. Please use b')

值得注意的是,PendingDeprecationWarning不会像正常异常一样停止执行。这是提出异常的结果:

PendingDeprecationWarning('a is deprecated in future update. Please use b',)

答案 2 :(得分:1)

您可以将kwargs传递给这样的函数:

def f(**kwargs):
    a = kwargs.get('a', 2)
    if 'a' in kwargs:
        print('Deprecation warning')
    b = kwargs.get('b', 2)

甚至:

def f(b=2, **kwargs):
    a = kwargs.get('a', 2)
    if 'a' in kwargs:
        print('Deprecation warning')