Using kwargs when writing functions

suggest change

You can define a function that takes an arbitrary number of keyword (named) arguments by using the double star ** before a parameter name:

def print_kwargs(**kwargs):
    print(kwargs)

When calling the method, Python will construct a dictionary of all keyword arguments and make it available in the function body:

print_kwargs(a="two", b=3)
# prints: "{a: "two", b=3}"

Note that the **kwargs parameter in the function definition must always be the last parameter, and it will only match the arguments that were passed in after the previous ones.

def example(a, **kw):
    print kw

example(a=2, b=3, c=4) # => {'b': 3, 'c': 4}

Inside the function body, kwargs is manipulated in the same way as a dictionary; in order to access individual elements in kwargs you just loop through them as you would with a normal dictionary:

def print_kwargs(**kwargs):
    for key in kwargs:
        print("key = {0}, value = {1}".format(key, kwargs[key]))

Now, calling print_kwargs(a="two", b=1) shows the following output:

print_kwargs(a = "two", b = 1)
key = a, value = "two"
key = b, value = 1

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


args and kwargs:
* Using kwargs when writing functions

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
83 args and kwargs
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve