HomeAboutRelease Notes

Call Functions with Dynamic Parameters in Python

March 27, 2022

When I was studying my colleague’s brilliant coding work, I noticed a very interesting implementation on calling functions with dynamic parameters in python.

import inspect # May come from anywhere such as HTTP / RPC calls, environment variables # where the format of params_from_anywhere is uncontrolled params_from_anywhere = { "a": "a value", "b": "b value", "c": "c value", "d": "d value", "e": "e value", "f": "f value", "g": "g value", "h": "h value", "i": "i value", } def fn_i_want_to_call(*, c=None, e=None, g=None, i=None, j=None): print(c) print(e) print(g) print(i) print(j) def call_fn_with_dynamic_params(fn, params): all_kwargs = inspect.getfullargspec(fn).kwonlyargs required_kwargs = {k: v for k, v in params.items() if k in all_kwargs} fn_i_want_to_call(**required_kwargs) call_fn_with_dynamic_params(fn_i_want_to_call, params_from_anywhere) # output: # c value # e value # g value # i value # None

It’s very interesting. It’s not calling fn_i_want_to_call function with specifying the parameters explicitly. Instead, it calls inspect.getfullargspec(fn).kwonlyargs to find out what the parameters are required in fn_i_want_to_call function and then dynamically map the parameters from a dictionary.

I feel it’s an interesting trick which can reduce the dumb manual parameter extractions from dictionary, so I made this demo code snippet and share to you all.

Written by Yi Zhiyue
A Software Engineer · 山不在高,有仙则灵
LinkedIn · GitHub · Email