mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
Clean-up example
This commit is contained in:
parent
4866266bf4
commit
b2269baca3
1 changed files with 11 additions and 5 deletions
|
@ -130,16 +130,22 @@ Example of simulating Python's internal lookup chain::
|
||||||
import builtins
|
import builtins
|
||||||
pylookup = ChainMap(locals(), globals(), vars(builtins))
|
pylookup = ChainMap(locals(), globals(), vars(builtins))
|
||||||
|
|
||||||
Example of letting user specified values take precedence over environment
|
Example of letting user specified command-line arguments take precedence over
|
||||||
variables which in turn take precedence over default values::
|
environment variables which in turn take precedence over default values::
|
||||||
|
|
||||||
import os, argparse
|
import os, argparse
|
||||||
defaults = {'color': 'red', 'user': guest}
|
|
||||||
|
defaults = {'color': 'red', 'user': 'guest'}
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument('-u', '--user')
|
parser.add_argument('-u', '--user')
|
||||||
parser.add_argument('-c', '--color')
|
parser.add_argument('-c', '--color')
|
||||||
user_specified = vars(parser.parse_args())
|
namespace = parser.parse_args()
|
||||||
combined = ChainMap(user_specified, os.environ, defaults)
|
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
|
Example patterns for using the :class:`ChainMap` class to simulate nested
|
||||||
contexts::
|
contexts::
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue