How to import __future__ for python 3.0 argument for keyword only?

The following code in python2.6 causes a 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 I should import in my interpreter for it to work. i.e. from import __future__ ????

to import print function from 3.0, I would do from __future__ import print_function

similarly, this definition is not valid in 2.6

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

while it is legal in version 3.0

+8
python python-import variadic-functions
source share
3 answers

This Python 3 compiler function was not sent back to Python 2.x.

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

Instead, your second function can be defined as:

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

for compatibility with Python 2.

+19
source share

The new syntax is discussed in PEP 3102 , and it is really invalid in Python 2.x.

However, you can get the keyword arguments from **kwargs manually:

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

Another alternative is to upgrade to Python 3.x.

+5
source share

Another way to emulate keyword-only -s arguments is:

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

If you do not want any unsolicited arguments to be 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 
+1
source share

All Articles