Hi list I have a proposal for a minor (improvement?) to dict declarations.
I find a common requirement I have is to include one or more entries in a dict only if some condition is met. Currently, the usual way of doing that is to add one or more if statements. Simple (but hopefully relatable-to-real-world-code) example. Here we're constructing a query for a database based on the arguments passed in. In some cases we don't want to include some fields in the search at all depending on what the values passed in are. ### def construct_query(user_id, max_results=10000, active=None, deleted=None): query = { 'user_id': user_id } if max_results > 0: query['max_results'] = max_results if active is not None: query['active'] = active if deleted is not None: query['deleted'] = deleted return query ### This is OK-ish, but seems unnecessarily verbose, and it gets worse if you have more conditional entries. In addition, you're separating the dict setup code into two or more places so it is slower to grasp mentally. This is a fairly common (tedious) pattern in my code, but I feel it could be avoided. In my view it would be better if it was possible to conditionally add the entry in the dict declaration. My proposal is that there should be a special value defined that results in a dict entry not being added to the dict if either the key or the value equals this value. There may be several ways to achieve this, but here's one way it could work. ### def construct_query(user_id, max_results=10000, active=None, deleted=False): return { 'user_id': user_id, 'max_results': max_results or dict.skip, 'active': active if active is not None else dict.skip, 'deleted': deleted if deleted is not None else dict.skip } ### ..."skip" being a unique object defined in and accessible from dict (there may be better places to make it available). The dict insertion code then simply ignores those entries when creating the dict. I think this would be relatively easy to achieve. No significant modification to the language, just a minor modification to the dict code (as far as I know). _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/OYYCR7E5SPRRVBRYQYPZXSUAVLB7BZSA/ Code of Conduct: http://python.org/psf/codeofconduct/