Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 786
brain storm Avatar asked Oct 30 '13 18:10

brain storm


People also ask

What is __ future __ In Python 3?

__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module.

Is print a keyword in Python?

Also, both print and exec were keywords in Python 2.7 but have been turned into built-in functions in Python 3+ and no longer appear in the list of keywords.

What is KWDS in Python?

Short answer: kwds is a dictionary. Longer answer: You can use *args and **kwargs to collect "extra" positional and keyword parameters. This is easier to demonstrate than explain, so I will try to illustrate with examples. Here's a function that takes two arguments: >>> def f(x, y): ... print x, y ...


1 Answers

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.

like image 126
Martijn Pieters Avatar answered Sep 18 '22 13:09

Martijn Pieters