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

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

  • 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

  • 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. anything preceding star args (*args) is interpreted as an arg (positional argument)
  2. 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}

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com