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

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

--

--

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