Explaining Function Calls with Stars Next to Argument Names

  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.

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

--

--

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

Pavol Kutaj

63 Followers

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