*args And **kwargs Forward Calls
A function with *args, keyword-only defaults, and **kwargs accepts extra positional names and keyword values, and call sites unpack them back.
Code
def audit(event, *tags, level="info", **fields):
print("event:", event)
print("tags:", tags)
print("level:", level)
print("fields:", fields)
audit("deploy", "prod", "blue", level="warn", revision=8192, actor="ci")
# * unpacks a sequence into positional arguments
positions = ("rollout", "canary")
audit(*positions)
# ** unpacks a mapping into keyword arguments
extra = {"level": "debug", "host": "web-1"}
audit("probe", **extra)
# A catch-all signature forwards everything verbatim
def relay(*args, **kwargs):
audit(*args, **kwargs)
relay("ping", "fast", level="trace")Output
Captured from a sandboxed run of this snippet in the build pipeline.
event: deploy
tags: ('prod', 'blue')
level: warn
fields: {'revision': 8192, 'actor': 'ci'}
event: rollout
tags: ('canary',)
level: info
fields: {}
event: probe
tags: ()
level: debug
fields: {'host': 'web-1'}
event: ping
tags: ('fast',)
level: trace
fields: {}How it works
*args And **kwargs Forward Calls comes down to the functions audit and relay.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
Signature: def audit(event, *tags, level="info", **fields)
The file announces its steps in the output: event:, tags:, level:.
audit is the public entry point; everything else in the file exists to support it.
The key statements, annotated
def audit(event, *tags, level="info", **fields):
print("event:", event)
print("tags:", tags)
print("level:", level)
print("fields:", fields)
def relay(*args, **kwargs):
audit(*args, **kwargs)
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `audit`, `relay` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.