Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

syntax

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

?

like image 803
kolypto Avatar asked Jan 12 '11 01:01

kolypto


3 Answers

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.

like image 119
S.Lott Avatar answered Sep 19 '22 10:09

S.Lott


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).

like image 32
Mikel Avatar answered Sep 17 '22 10:09

Mikel


*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>
like image 26
Amber Avatar answered Sep 18 '22 10:09

Amber