Unpacking function arguments

suggest change

When you want to create a function that can accept any number of arguments, and not enforce the position or the name of the argument at “compile” time, it’s possible and here’s how:

def fun1(*args, **kwargs):
    print(args, kwargs)

The *args and **kwargs parameters are special parameters that are set to a tuple and a dict, respectively:

fun1(1,2,3)
# Prints: (1, 2, 3) {}
fun1(a=1, b=2, c=3)
# Prints: () {'a': 1, 'b': 2, 'c': 3}
fun1('x', 'y', 'z', a=1, b=2, c=3)
# Prints: ('x', 'y', 'z') {'a': 1, 'b': 2, 'c': 3}

If you look at enough Python code, you’ll quickly discover that it is widely being used when passing arguments over to another function. For example if you want to extend the string class:

class MyString(str):
    def __init__(self, *args, **kwarg):
        print('Constructing MyString')
        super(MyString, self).__init__(*args, **kwarg)

Feedback about page:

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


List destructuring:
* Unpacking function arguments

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
116 List destructuring
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