*args and **kwargs

Run Settings
LanguagePython
Language Version
Run Command
''' *args and **kwargs are some of the most confusing concepts when learning Python. Firstly, "args" and "kwargs" are just dummy variables. They can be replaced by x, j, booty, anything you want. But, for the sake of semantics and good practice, "args" stands for arguments and "kwargs" stands for keyword arguments. Secondly, * and ** are actually operators, not part of the variables themselves. When they are not used on function argument: 1. * unpacks iterables, meaning that if we have a list [1, 2, 3], *[1, 2, 3] = 1, 2, 3. 2. ** unpacks dicts. When they *are* used on function arguments, however, they do the exact opposite: they repack arguments. For all non-keyword arguments that do not correspond to a positional argument, * packs them into a tuple. For all keyword arguments that don't correspond to an existing keyword argument, ** packs them into a dict. ''' # UNPACKING: # lists, tuples, sets (although tuples and frozensets are immutable, so be careful) def unpack_list(i, j, k): print(i, j, k) l = [1, 2, 3] unpack_list(*l) # dicts def unpack_dict(first, last): print(first, last) dude = { 'first': 'Marc', 'last': 'Antony' } unpack_dict(**dude) # PACKING: # normal function parameters def pack_unkeyed_args(*args): for a in args: print(a) pack_unkeyed_args(1, 2, 3) # named function parameters def pack_named_args(**booty): for b in booty: print(b, booty[b]) pack_named_args(first='Marc', last='Gotcha') ''' However, since functions rely on explicit order for positional arguments, you can't put *args or **kwargs before any positional arguments. Like so: def bad(name='bad', *args, **kwargs, that, thing): for a in args: print(a) for k in kwargs: print(k, kwargs) print(name) bad(2, 3, 4, 5) # SyntaxError: invalid syntax ''' ''' This is a messy example and *really* bad code, but it serves its purpose. ''' def good(this, that, name='good', *args, **kwargs): print(this, that, name) print('bundled in args') for a in args: print(a) print('bundled in kwargs') for k in kwargs: print(k, kwargs[k]) good(1, 2, 6, 7, 8, first='first', second='second')
Editor Settings
Theme
Key bindings
Full width
Lines