How to Pass a Single Dictionary Instead of Many Arguments into a Function in Python
on the usefulness of calling function(**arguments)
1 min readSep 22, 2022
The aim of this page📝 is to learn from this encounter in code that goes something like
options = {
"statsd_host": os.environ["STATSD_HOST"],
"statsd_port": int(os.environ["STATSD_PORT"])
}
datadog.initialize(**options)
- In summary, this is a pretty cool way of passing concise function calls (Uncle Bob would cap the arg count to 3)
- The code means that the
initialize()
the method must contain parameters calledstatsd_host
,statsd_port
- And, surely,
statsd_host
andstatsd_port
are listed as params in the monstrous function in the API docs:
datadog.initialize(api_key=None, app_key=None, host_name=None, api_host=None, >>> statsd_host=None, statsd_port=None <<<, statsd_disable_buffering=True, statsd_use_default_route=False, statsd_socket_path=None, statsd_namespace=None, statsd_constant_tags=None, return_raw_response=False, hostname_from_config=True, **kwargs)
- The called method
initialize()
is mapping the dictionary keys from theoptions
variable to parameter names within its own function definition and thus accessing passed values - The coolness is that you can then extend the
options
dictionary without modifying the function call - As a side note, note the permissiveness of the
initialize()
function:
- none of the arguments are required as all have a default value set to
None
- There also is
**kwargs
at the end of the function definition; i.e. you can pass a random number of dictionaries
LINKS
- https://pavolkutaj.medium.com/use-kwargs-to-accept-an-arbitrary-number-of-keyword-arguments-b6711ff8090a
- https://medium.com/p/13a82675f026
- https://datadogpy.readthedocs.io/en/latest/#datadog.initialize
- https://medium.com/mindorks/how-to-write-clean-code-lessons-learnt-from-the-clean-code-robert-c-martin-9ffc7aef870c#41e3