Explaining Function Calls with Stars Next to Argument Names

How function unpacks foo(*arr) OR foo(**dictionary) aka “Extended function call syntax”

Pavol Kutaj
2 min readFeb 26, 2022

The aim of this page📝is to complement the extended formal argument (i.e. parameter) syntax (*args) and (**kwargs) with the extended call (i.e. argument) syntax — the enablement of unpacking an argument within a call to multiple single parameters or starred parameters in a function definition. There are 2 types

  1. series/collections (lists, tuples) to populate positional arguments
  2. mappings (dicts) to populate keyword arguments
  • NOTE: Even though there may be a visual symmetry between the */** a parameter in the function definition and */** in the function call, there is no necessary 1:1 correspondence between the two. The values within the call may unpack to multiple arguments. Only the remaining entries are bundled into starred parameters in the definition. There are plenty of combinations of how can this be used. Let's demonstrate with examples.

For more fun, follow the links below.

1. SERIES

  • you can pass the iterable series with * as an argument of a function call as well
""" FUNCTION DEFINITION WITH *ARGSS """
def print_args(arg1, arg2, *args):
print(arg1)
print(arg2)
print(args)

t = (11,12,13,14)

""" FUNCTION CALL WITH THE MATCHED * PREFIX ARGUMENT """
print_args(*t)

# 11
# 12
# (13, 14)

""" FUNCTION DEFINITION WITHOUT *ARGS """
def print_args(arg1, arg2):
print(arg1)
print(arg2)

""" FUNCTION CALL WITH * """
>>> a = ("hello", "world")
>>> print_args(*a)
# hello
# world
  • this maps the content of the collection to the parameters of the function definition

2. MAPPINGS

""" FUNCTION DEFINITION WITH **KWARGS """
def color(red, green, blue, **kwargs):
print("r = ", red)
print("g = ", green)
print("b = ", blue)
print(kwargs)
k = {
'red':21,
'green':68,
'blue':120,
'alpha':52
}
""" FUNCTION CALL WITH MATCHED ** PREFIX ARGUMENT"""
color(**k)
# r = 21
# g = 68
# b = 120
# {'alpha': 52}
```
```python
""" FUNCTION DEFINITION WITHOUT **KWARGS """
def color(red, green, blue):
print("r = ", red)
print("g = ", green)
print("b = ", blue)
k = {
'red':21,
'green':68,
'blue':120,
}
""" FUNCTION CALL WITH MATCHED ** PREFIX ARGUMENT"""
color(**k)
# r = 21
# g = 68
# b = 120

3. LINKS

--

--

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