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

这一生的挚爱 提交于 2019-12-01 15:07:39

问题


The following code in python2.6 throws syntax error

>>> def f(a,*args,c):
  File "<stdin>", line 1
    def f(a,*args,c):
                  ^
SyntaxError: invalid syntax

but this syntax is valid in python3.0. I would like to know what should I import in my interpreter to make it work. ie. from import __future__ ????

for importing print function of 3.0, I would do from __future__ import print_function

similarly this defination is invalid in 2.6

def f(a,*b,c=5,**kwargs):

while it is legal in 3.0


回答1:


This feature of the Python 3 compiler has not been backported to Python 2.x.

There is no magic from __future__ import switch to enable it, your only option is to upgrade to Python 3.x.

Your second function could instead be defined as:

def (a, *b, **kwargs):
   c = kwargs.pop('c', 5)

to be Python 2 compatible.




回答2:


The new syntax is discussed in PEP 3102 and it's indeed not valid in Python 2.x.

However you can obtain the keyword arguments from **kwargs manually:

def f(a, *b, **kwargs):
    if 'c' in kwargs:
        pass

The other alternative is to upgrade to Python 3.x.




回答3:


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


来源:https://stackoverflow.com/questions/19690483/how-to-import-future-for-keyword-only-argument-of-python-3-0

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