marcman
marcman

Reputation: 3393

Name of and reason for Python function parameters of type `name=value`

It's entirely possible that this question is a duplicate, but I don't know what this concept is called so I don't even know how to search for it.

I'm new to Python and trying to understand this function from a Caffe example:

def conv_relu(bottom, ks, nout, stride=1, pad=0, group=1):
    conv = L.Convolution(bottom, kernel_size=ks, stride=stride,
                                num_output=nout, pad=pad, group=group)
    return conv, L.ReLU(conv, in_place=True)

I figured the parameters stride=1, pad=1, etc in the conv_relu function definition are default initial values, but then what do kernel_size=ks, stride=stride, etc in the L.Convolution call mean? Is it kind of like a name/value pair?

If nothing else, can someone please tell me what this is called?

Upvotes: 5

Views: 154

Answers (3)

Dun Peal
Dun Peal

Reputation: 17739

In Python, arguments can be provided by position, or by keyword.

For example, say you have the following function:

def foo(bar, baz=1, qux=2):
    pass

You can call it as foo(3), so in the callee scope, bar would be 3. baz and qux will be assigned their default values - 1 and 2, respectively - so you don't have to provide them explicitly.

You can also call this function using keyword arguments (that's the term you were searching for). The exact same call with bar as a named argument would be foo(bar=3).

Of course, we would rather just use foo(3) since it's more concise, unless there are specific reasons to use named arguments. An example of such reason is if we wish to provide a non-default argument for qux, while leaving the default argument for baz unchanged: foo(3, qux=4).

Upvotes: 4

Carcigenicate
Carcigenicate

Reputation: 45826

Those are keyword arguments.

some_function(x=y, z=zz) 

x is the name of the parameter when the function was declared, and y is the value that's being passed in.

Reasons to use keyword arguments:

  • You can give them in any order, instead of only the order in the function definition
  • When you look back on the code later, if the parameters have good names, you can immediately tell the purpose of the passed variables instead of needing to check the function definition or documentation to see what the data means.

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1124788

You have a call expression using keyword arguments. Each name=value pair assigns a value to a specific parameter the function accepts.

Keyword arguments can be used in any order. If the named parameter in the function signature has a default value, the value in the call overrides that default. If you omit a specific argument, the default value is used.

Upvotes: 5

Related Questions