From: Raymond Hettinger Date: Mon, 16 Jul 2012 06:53:32 +0000 (-0700) Subject: Clean-up example X-Git-Tag: v3.3.0b2~188 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=b2269baca3da855179c927a87f0703ec6b447f7e;p=python Clean-up example --- diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 3c1a8bf220..c15885e574 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -130,16 +130,22 @@ Example of simulating Python's internal lookup chain:: import builtins pylookup = ChainMap(locals(), globals(), vars(builtins)) -Example of letting user specified values take precedence over environment -variables which in turn take precedence over default values:: +Example of letting user specified command-line arguments take precedence over +environment variables which in turn take precedence over default values:: import os, argparse - defaults = {'color': 'red', 'user': guest} + + defaults = {'color': 'red', 'user': 'guest'} + parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') - user_specified = vars(parser.parse_args()) - combined = ChainMap(user_specified, os.environ, defaults) + namespace = parser.parse_args() + command_line_args = {k:v for k, v in vars(namespace).items() if v} + + combined = ChainMap(command_line_args, os.environ, defaults) + print(combined['color']) + print(combined['user']) Example patterns for using the :class:`ChainMap` class to simulate nested contexts::