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

It is very 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 look for it.

I am new to Python and trying to understand this function from 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 realized that the parameters are stride=1 , pad=1 , etc. in the definition of the function conv_relu are the initial default values, but then what does kernel_size=ks , stride=stride , etc. mean kernel_size=ks in calling L.Convolution ? Is it like a pair of names / values?

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

+5
source share
3 answers

These are keyword arguments.

 some_function(x=y, z=zz) 

x is the name of the parameter when declaring the function, and y is the value that is passed.

Reasons for using keyword arguments:

  • You can give them in any order, and not just in the function definition
  • When you look back at the code later, if the parameters have good names, you can immediately indicate the purpose of the passed variables instead of checking the function definition or documentation to see what the data means.
+6
source

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

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 value. If you omit a specific argument, the default value is used.

+5
source

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

For example, let's say that you have the following function:

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

You can name it as foo(3) , so there will be 3 in the scope of the called side bar . baz and qux will be assigned the default values ​​of 1 and 2 respectively, so you do not need to explicitly specify them.

You can also call this function using the keyword arguments (the term you were looking for). The exact call with bar as a named argument will be foo(bar=3) .

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

+4
source

Source: https://habr.com/ru/post/1245389/


All Articles