forcing keyword arguments in python 2.7

喜你入骨 提交于 2019-12-06 03:22:09

One way of doing this is by adding a dummy keyword argument that never gets a valid positional value (so don't check for None):

_dummy = object()

def abc(a, dummy_kw=_dummy, x=10, z=30):
    if dummy_kw is not _dummy:
        raise TypeError("abc() takes 1 positional argument but at least 2 were given")

That will prohibit abc(7, 13) and allow all the others. It works on Python 2 and Python 3, so it is useful when you have code that needs to run on both.

Originally I used:

 def _dummy():
    pass

but as @mata pointed out _dummy=object() works as well, and cleaner. Essentially any unique memory location that is not used in another way will work.

What about the following:

def abc(a, **kwargs):
    # Get arguments from kwargs otherwise use default values
    x = kwargs.pop('x', 10) 
    z = kwargs.pop('z', 30) 

    if not kwargs: # if kwargs is not empty
        print 'extra parameters passed'

    pass

This allows to force the use of kwargs and still have default values.

pop removes the key from kwargs, once you use it. This is potentially very useful as you can check if the user gave extra parameters that do not belong to the function and in this case you can throw an error (for example).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!