SoFunction
Updated on 2025-03-03

Detailed explanation of python parameter kwargs and usage

python pass-through kwargs

There are many similar uses in Python code, and I still had a lot of doubts when I first came across it. In order to facilitate memory, I sorted out it out.

# Use the model to reasonwith torch.no_grad():
    outputs = model(**encoded_texts)

For a dict type variable**encoded_textsIt is to take out the value value without considering the key.

def test_func(**kwargs):
    a = kwargs["a"]
    b = kwargs["b"]
    print(a)  # [1, 2, 3]
    print(b)  # hello test
dct = {"a": [1, 2, 3], "b": "hello test"}
test_func(**dct)

When passing the parameter, the parameter transfer form is simplified without specifying the parameter name.

Parameter pass of Python functions *args and **kwargs

Knowledge points:

  • When a function is called, * will unpack a ancestral in the form of a single element to make it an independent parameter.
  • When a function is called, ** will unpack a dictionary in the form of a key/value pair to make it an independent keyword parameter.
def f(a,*args):
    print(args)

f(1,2,3,4)
​```
The output is:(2, 3, 4)
​```

Although 1, 2, 3, 4 is passed in, but the unpackage is (1), (2, 3, 4), where a is 1 and args is the remaining.

In python, when the * and ** symbols appear in the parameters defined by the function, they represent any number of parameters. *arg represents any multiple nameless parameters, type tuple; **kwargs represents keyword parameters, which is dict. When using it, you need to place arg before *kwargs, otherwise there will be a syntax error of "SyntaxError: non-keyword arg after keyword arg".

Let's take a look at the example of parameter passing of **kwargs

def f(**kargs):
    print(kargs)
f(a=1,b=2) # The actual parameters are two, but are wrapped together​```output:
{'a': 1, 'b': 2}
​```
def person(name,age,**kw):
    print('name:',name,'age:',age,'other:',kw)
# Pass in 4 parameters and automatically splice the last two digits into a dictionaryperson('Adam', 45, gender='M', job='Engineer')
​```output
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
​```

Let's take a look at the example of *args and **kwargs mixing examples

def h(a,*args,**kwargs):
    print(a,args,kwargs)
h(1,2,3,x=4,y=5)
# Throw in the package with uncertain parameters: 1, 2, 3, x=4, y=5# Unpacking: 1 -a# Unpacking: (2,3) -*args# Unpacking: {'x': 4, 'y': 5} -**kwargs​```output
1 (2, 3) {'x': 4, 'y': 5}
​```

This is the end of this article about pytho transfer kwargs. For more related content about pytho transfer kwargs, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!