What's the difference between arguments with default values and keyword-arguments?
Asked Answered
C

5

13

In Python, what's the difference between arguments having default values:

def f(a,b,c=1,d=2): pass

and keyword arguments:

def f(a=1,b=2,c=3): pass

? I guess there's no difference, but the tutorial has two sections:

4.7.1. Default Argument Values

4.7.2. Keyword Arguments

which sounds like there are some difference in them. If so, why can't I use this syntax in 2.6:

def pyobj_path(*objs, as_list=False): pass

?

Columniation answered 12/1, 2011 at 1:48 Comment(0)
H
17

Keyword arguments are how you call a function.

f( a=1, b=2, c=3, d=4 )

Default values are how a function is defined.

Hyperspace answered 12/1, 2011 at 1:52 Comment(1)
Or, keyword arguments are actual parameters and default values are formal parameters.Enciso
F
11

Default arguments mean you can leave some parameters out. Instead of f(1, 2, 3) you can just write f(1) or f(1, 2).

Keyword arguments mean you don't have to put them in the same order as the function definition. Instead of f(1, 2, 3) you can do f(c=3, b=2, a=1).

Facet answered 12/1, 2011 at 1:58 Comment(0)
R
8

*args and/or **kwargs must always come at the end of the argument list in a function declaration, if they are present. Specifically:

def <function name>(
        [<args without defaults>,]
        [<args with defaults>,]
        [*<variable length positional argument list name>,]
        [**<arbitrary keyward argument dict name>]
    ):
    <function body>
Ramp answered 12/1, 2011 at 2:17 Comment(0)
P
4

Default values for parameters are set when defining the function with def. It makes passing those arguments optional when calling the function

Define function with default value for last parameter:

def name_of_function(parameter0, parameter1, default_parameter1 = 'value')

Parameters with default values should only be placed after simple parameters.

Call above function (Note: argument values for parameters with default values is optional):

name_of_function(parameter0, parameter1) 

Same function called with keyword arguments:

name_of_function(parameter1='value1', parameter0='value0')

Keyword arguments are simple arguments. When calling a function, you could supply name-value pairs of parameter_name=value instead of just the value. This allows you to supply the arguments in a function call in any order.

Porcupine answered 9/10, 2016 at 0:47 Comment(0)
S
0

Keyword arguments are entirely independent of default argument values.

For example, you can define a function with no default argument values and still use keyword arguments when you call it:

>>> def g(a,b,c):
...     print(a,b,c)
... 
>>> g(0,1,2)
0 1 2
>>> g(b=2,a=1,c=0)
1 2 0

That said, I agree that the overly complicated examples given in the Python tutorial do not make this clear!

Splashy answered 16/8 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.