New submission from Jonathan Scholbach <j.scholb...@posteo.de>:

Below "Examples and Recipes", the Documentation of collections.ChainMap has an 
"Example of letting user specified command-line arguments take precedence over 
environment variables which in turn take precedence over default values:" In 
there, a ChainMap is created which represents the default values, updated by 
the command-line arguments, if they have been set. The relevant code snippet is 
the following:
   
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--user')
    parser.add_argument('-c', '--color')
    namespace = parser.parse_args()
    command_line_args = {k:v for k, v in vars(namespace).items() if v}

If user passes an empty string as value for any of the command-line arguments, 
that argument would not appear in `command_line_args` (because the boolean 
value of empty string is `False`). However, passing the empty string as a value 
for a command-line argument, would reflect the intent of overwriting the 
default value (setting it to the empty string). With the current example code, 
this would erroneously not be reflected in the `command_line_args`. This is 
caused by checking for the boolean of `v` instead of checking for `v` not being 
`None`. So, this should be handled correctly by writing

    command_line_args = {k: v for k, v in vars(namespace).items() if v is not 
None}

----------
assignee: docs@python
components: Documentation
messages: 356398
nosy: docs@python, jonathan.scholbach
priority: normal
severity: normal
status: open
title: Bug in example of collections.ChainMap
versions: Python 3.5, Python 3.6, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue38771>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to