Use **kwargs To Accept An Arbitrary Number Of Keyword Arguments in Python

Pavol Kutaj
2 min readFeb 23, 2022

The aim of this pageđź“ťis to define the means for the acceptance or an arbitrary number of keyword arguments in python functions.

Useful in situations when you don’t know how many arguments there will be and the function has to be able to accept as many as possible.

1. ANATOMY

  • in a function definition, prefix a parameter with **
  • conventionally, this is called **kwargs — star kwargs
  • depending on your situation, you may care to choose a more meaningful name (see below)
  • the **kwargs is a dictionary (as opposed to *args which is a tuple)
  • in **kwargs, arguments are transferred to keyword arguments as a regular python dictionary
  • each key is a string bearing the actual argument name
def tag(name, **kwargs):
print(name)
print(kwargs)
print(type(kwargs))

>>> tag('img', src='screenshot.png', alt='Desktop screenshot', border=1)
# img
# {'src': 'screenshot.jpg', 'alt': 'Desktop screenshot', 'border': 1}
# <class 'dict'>

2. IMPLEMENTATION

  • note that it is possible to combine positional arguments with keyword arguments (see rules below)
  • the overall syntax is very powerful
def html_tag_implement(name, **attributes):
result = '<' + name
for key, value in attributes.items():
result += f" {key} = \"{str(value)}\""
result += '>'
print(result)

html_tag_implement('img', src='screenshot.jpg',
alt='Desktop screenshot', border=1)

# <img src = "screenshot.jpg" alt = "Desktop screenshot" border = "1">

3. RULES

  1. order matters: same as a single positional arg precede single keyword argument kwarg, star args (*args) precede star kwargs (**kwargs)
  2. anything preceding star args (*args) is interpreted as an arg (positional argument)
  3. anything following star args (*args) is interpreted as mandatory kwarg (keyword argument)
  • failure to pass them as keyword arguments results in type error
print_args(arg1,arg2,*args,kwarg1,kwarg2):
print(arg1)
print(arg2)
print(args)
print(kwarg1)
print(kwarg2)

>>> print_args(1,2,3,4,5,kwarg1=6,kwarg2=7)
1
2
(3,4,5)
6
7

4. star kwargs (**kwargs) — if present — must be very last in the argument list. Any attempt at passing an argument after **kwargs results in a syntax error

print_args(arg1,arg2,*args,kwarg1,kwarg2,**kwargs):
print(arg1)
print(arg2)
print(args)
print(kwarg1)
print(kwarg2)

>>> print_args(1,2,3,4,5,kwarg1=6,kwarg2=7,kwarg3=8,kwarg4=9)
1
2
(3,4,5)
6
7
{'kwarg3': 8, 'kwarg4': 9}

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com