Kaydet (Commit) bfcb4293 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

Expand examples for ChainMap(). Improve markup.

üst 9253862f
...@@ -93,13 +93,44 @@ The class can be used to simulate nested scopes and is useful in templating. ...@@ -93,13 +93,44 @@ The class can be used to simulate nested scopes and is useful in templating.
The use-cases also parallel those for the builtin :func:`super` function. The use-cases also parallel those for the builtin :func:`super` function.
A reference to ``d.parents`` is equivalent to: ``ChainMap(*d.maps[1:])``. A reference to ``d.parents`` is equivalent to: ``ChainMap(*d.maps[1:])``.
Example of simulating Python's internal lookup chain::
.. seealso::
* The `MultiContext class
<http://svn.enthought.com/svn/enthought/CodeTools/trunk/enthought/contexts/multi_context.py>`_
in the Enthought `CodeTools package
<https://github.com/enthought/codetools>`_ has options to support
writing to any mapping in the chain.
* Django's `Context class
<http://code.djangoproject.com/browser/django/trunk/django/template/context.py>`_
for templating is a read-only chain of mappings. It also features
pushing and popping of contexts similar to the
:meth:`~collections.ChainMap.new_child` method and the
:meth:`~collections.ChainMap.parents` property.
* The `Nested Contexts recipe
<http://code.activestate.com/recipes/577434/>`_ has options to control
whether writes and other mutations apply only to the first mapping or to
any mapping in the chain.
* A `greatly simplified read-only version of Chainmap
<http://code.activestate.com/recipes/305268/>`_.
:class:`ChainMap` Examples and Recipes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This section shows various approaches to working with chained maps.
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 values take precedence over environment
variables which in turn take precedence over default values:: 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}
...@@ -109,8 +140,8 @@ The class can be used to simulate nested scopes and is useful in templating. ...@@ -109,8 +140,8 @@ The class can be used to simulate nested scopes and is useful in templating.
user_specified = vars(parser.parse_args()) user_specified = vars(parser.parse_args())
combined = ChainMap(user_specified, os.environ, defaults) combined = ChainMap(user_specified, os.environ, defaults)
Example patterns for using the :class:`ChainMap` class to simulate nested Example patterns for using the :class:`ChainMap` class to simulate nested
contexts:: contexts::
c = ChainMap() # Create root context c = ChainMap() # Create root context
d = c.new_child() # Create nested child context d = c.new_child() # Create nested child context
...@@ -128,28 +159,33 @@ The class can be used to simulate nested scopes and is useful in templating. ...@@ -128,28 +159,33 @@ The class can be used to simulate nested scopes and is useful in templating.
d.items() # All nested items d.items() # All nested items
dict(d) # Flatten into a regular dictionary dict(d) # Flatten into a regular dictionary
.. seealso:: The :class:`ChainMap` class only makes updates (writes and deletions) to the
first mapping in the chain while lookups will search the full chain. However,
* The `MultiContext class if deep writes and deletions are desired, it is easy to make a subclass that
<http://svn.enthought.com/svn/enthought/CodeTools/trunk/enthought/contexts/multi_context.py>`_ updates keys found deeper in the chain::
in the Enthought `CodeTools package
<https://github.com/enthought/codetools>`_ has options to support
writing to any mapping in the chain.
* Django's `Context class
<http://code.djangoproject.com/browser/django/trunk/django/template/context.py>`_
for templating is a read-only chain of mappings. It also features
pushing and popping of contexts similar to the
:meth:`~collections.ChainMap.new_child` method and the
:meth:`~collections.ChainMap.parents` property.
* The `Nested Contexts recipe class DeepChainMap(ChainMap):
<http://code.activestate.com/recipes/577434/>`_ has options to control 'Variant of ChainMap that allows direct updates to inner scopes'
whether writes and other mutations apply only to the first mapping or to
any mapping in the chain.
* A `greatly simplified read-only version of Chainmap def __setitem__(self, key, value):
<http://code.activestate.com/recipes/305268/>`_. for mapping in self.maps:
if key in mapping:
mapping[key] = value
return
self.maps[0][key] = value
def __delitem__(self, key):
for mapping in self.maps:
if key in mapping:
del mapping[key]
return
raise KeyError(key)
>>> d = DeepChainMap({'zebra': 'black'}, {'elephant' : 'blue'}, {'lion' : 'yellow'})
>>> d['lion'] = 'orange' # update an existing key two levels down
>>> d['snake'] = 'red' # new keys get added to the topmost dict
>>> del d['elephant'] # remove an existing key one level down
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})
:class:`Counter` objects :class:`Counter` objects
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment