how to import __future__ for keyword-only argument of python 3.0?

前端 未结 3 1691
感动是毒
感动是毒 2021-01-17 19:58

The following code in python2.6 throws syntax error

>>> def f(a,*args,c):
  File \"\", line 1
    def f(a,*args,c):
                  ^         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 20:50

    Another way to emulate keyword-only-arguments is:

    def f(a, *args, **kwds):
        b = kwds.get('b', 42) # 42 being the default for b
    

    if you wan't to make sure that no unsolicited arguments are passed you can use pop instead:

    def f(a, *args, **kwds):
        b = kwds.pop('b', 42)
    
        assert not kwds # after we've popped all keywords arguments kwds should be empty
    

提交回复
热议问题