I'm trying to generate a dict containing the names and the value of the non-None
parameters current call. This very much feels like something that should be a built-in, but can't find anything that quite does it in the Python documentation.
For example, when
def foo(limit=None, offset=None, lower_bound=None, upper_bound=None):
# code to generate dict of non-`None` named arguments (see below)
... # other things happen later
is called with the parameters foo(limit=5, lower_bound=100)
, I need the following dict: {limit=5, lower_bound=100}
.
Is there something that conveniently does that for me?
Potential Solutions
So far, I have looked into the following, all of which seem flawed:
- Manually making lists (which has a downside of having more places to things to make changes if, for example, an argument has its name changed)
def foo(limit=None, offset=None, lower_bound=None, upper_bound=None):
keys = ('limit', 'offset', 'lower_bound', 'upper_bound')
values = (limit, offset, lower_bound, upper_bound)
magic_dict = {k: v for k, v in zip(keys, values) if v is not None}
locals()
— link — which would need everything removed that shouldn't make it into the dictionary (i.e. the keys with the value ofNone
). This also seems potentially error prone if variables definitions get added above the magic dictionary code, which would also need to be removed.
def foo(limit=None, offset=None, lower_bound=None, upper_bound=None):
magic_dict = {k: v for k, v in locals().items() if v is not None}
inspect
's — link —signature
andbind
, which still requires would a list of the parameters
def foo(limit=None, offset=None, lower_bound=None, upper_bound=None):
sig = signature(foo)
sig_args = sig.bind(limit, offset, lower_bound, upper_bound).arguments
magic_dict = {k: v for k, v in sig_args.items() if v is not None}
Other thoughts included making a class to make getattr
available
It feels like I'm missing something obvious — feedback would be appreciated!
Someone suggested
What is an elegant way to select all non-None elements from parameters and place them in a python dictionary?, whose responses are primarily "move to **kwargs
". My initial reaction is that I would prefer to keep a specific list of arguments — is that bad logic by me? What is typical best practice with Python?