How to Pass a Single Dictionary Instead of Many Arguments into a Function in Python

on the usefulness of calling function(**arguments)

Pavol Kutaj
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)
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 the options 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:
  1. none of the arguments are required as all have a default value set to None
  2. There also is **kwargs at the end of the function definition; i.e. you can pass a random number of dictionaries

LINKS

--

--

No responses yet