I think I've seen *args and **kwargs in other people's source code, but I've no idea what they do :(

My Python experience is limited to using is as a fancy calculator and some quick-and-dirty scripting, I basically do not know Python

Follow

@vaporeon_ the names are conventional but the only impurrtant part is the * and **. a * arg is basically variadic arguments:

def fun(a, *args):
...

takes one required argument and any number of optional arguments, available in fun as a list bound to args

understanding the ** argument requires furst understanding the notion of "keyword" arguments. it is allowed to invoke the above function as fun(a=1). if it took mulitple arguments, i could supply keyword arguments in arbitrary order:

def fun2(a, b):
return b

fun2(1, 2) # 2
fun2(b=1, a=2) # 1

normally, it is a TypeError to supply an unexpected keyword argument to a function, but if there is a ** argument to the function, it is bound to a dict available the ** argument`s name:

def fun(**kwargs)
return kwargs

fun(a=2, b=3) # {'a': 2, 'b': 3}

an extremely common pattern is to write a thin wrapper around another existing function that takes keyword arguments. python has convenient syntax for inserting keyword arguments into a function call from a dict:

import requests

BASE_URI = # ...

def get(path, **kwargs):
# the HTTP methods in the requests library take a large number of optional keyword arguments
return requests.get(f"{BASE_URI}{path}", **kwargs)

auth_headers = # ...
print(get("/api/records", headers=auth_headers).json())
Sign in to participate in the conversation
📟🐱 GlitchCat

A small, community‐oriented Mastodon‐compatible Fediverse (GlitchSoc) instance managed as a joint venture between the cat and KIBI families.