Why this code works in python3, but not python 2:

  • Thread starter Maciej Dziardziel
  • Start date
M

Maciej Dziardziel

Out of curiosity: Does anyone know why the code below is valid in python3, but not python2:

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

Chris Angelico

Out of curiosity: Does anyone know why the code below is valid in python3, but not python2:

def foo(*args, bar=1, **kwargs):
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
 
J

Joshua Landau

Out of curiosity: Does anyone know why the code below is valid in python3, but not python2:

def foo(*args, bar=1, **kwargs):
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.
 
A

alex23

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top