Discussion:
Why this code works in python3, but not python 2:
(too old to reply)
Maciej Dziardziel
2013-07-04 03:52:43 UTC
Permalink
Out of curiosity: Does anyone know why the code below is valid in python3, but not python2:

def foo(*args, bar=1, **kwargs):
pass
--
Maciej Dziardziel
alex23
2013-07-04 04:05:23 UTC
Permalink
pass
It was an explicit syntax change for Python3. You can read about the
reasoning behind it here:

http://www.python.org/dev/peps/pep-3102/
Maciej Dziardziel
2013-07-04 04:31:51 UTC
Permalink
Post by alex23
It was an explicit syntax change for Python3. You can read about the
http://www.python.org/dev/peps/pep-3102/
Thanks, that was helpful.

Maciej Dziardziel
Chris Angelico
2013-07-04 04:10:39 UTC
Permalink
pass
Keyword-only arguments are (IIRC) a Py3-only feature. There are lots
of features that don't work in Python 2 - that's simply the way things
happen with old versions of software.

ChrisA
Joshua Landau
2013-07-04 04:12:26 UTC
Permalink
pass
Python 3 gained syntax for keyword-only arguments.

Try "foo(1)" and it will fail -- "bar" needs to be given as a keyword.
This is because it comes after a *-expression. You can also do "def
foo(*, bar=1)" if you want bar to be keyword-only without accepting
any number of positional arguments. Python 2 does not have these, and
doesn't understand the syntax for them.
alex23
2013-07-04 04:47:03 UTC
Permalink
Post by Joshua Landau
pass
Try "foo(1)" and it will fail -- "bar" needs to be given as a keyword.
No it won't, because it is supplied with a default. You may be
confusing it with the requirement that `bar` must be given as a keyword
in order for it to override the default, compared to the way this would
need to be written in Py2:

def foo(bar=1, *args, **kwargs):
...

...in which case `bar` could be assigned to by the first positional
argument.
Joshua Landau
2013-07-04 05:10:21 UTC
Permalink
Post by alex23
Post by Joshua Landau
pass
Try "foo(1)" and it will fail -- "bar" needs to be given as a keyword.
No it won't, because it is supplied with a default.
Pah! I'm not even thinking.

Continue reading on narkive:
Loading...