Skip to content
Projeler
Gruplar
Parçacıklar
Yardım
Yükleniyor...
Oturum aç / Kaydol
Gezinmeyi değiştir
C
cpython
Proje
Proje
Ayrıntılar
Etkinlik
Cycle Analytics
Depo (repository)
Depo (repository)
Dosyalar
Kayıtlar (commit)
Dallar (branch)
Etiketler
Katkıda bulunanlar
Grafik
Karşılaştır
Grafikler
Konular (issue)
0
Konular (issue)
0
Liste
Pano
Etiketler
Kilometre Taşları
Birleştirme (merge) Talepleri
0
Birleştirme (merge) Talepleri
0
CI / CD
CI / CD
İş akışları (pipeline)
İşler
Zamanlamalar
Grafikler
Paketler
Paketler
Wiki
Wiki
Parçacıklar
Parçacıklar
Üyeler
Üyeler
Collapse sidebar
Close sidebar
Etkinlik
Grafik
Grafikler
Yeni bir konu (issue) oluştur
İşler
Kayıtlar (commit)
Konu (issue) Panoları
Kenar çubuğunu aç
Batuhan Osman TASKAYA
cpython
Commits
bfcb4293
Kaydet (Commit)
bfcb4293
authored
Haz 10, 2012
tarafından
Raymond Hettinger
Dosyalara gözat
Seçenekler
Dosyalara Gözat
İndir
Eposta Yamaları
Sade Fark
Expand examples for ChainMap(). Improve markup.
üst
9253862f
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
74 additions
and
38 deletions
+74
-38
collections.rst
Doc/library/collections.rst
+74
-38
No files found.
Doc/library/collections.rst
Dosyayı görüntüle @
bfcb4293
...
@@ -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,
if deep writes and deletions are desired, it is easy to make a subclass that
updates keys found deeper in the chain::
* The `MultiContext class
class DeepChainMap(ChainMap):
<http://svn.enthought.com/svn/enthought/CodeTools/trunk/enthought/contexts/multi_context.py>`_
'Variant of ChainMap that allows direct updates to inner scopes'
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
def __setitem__(self, key, value):
<http://code.djangoproject.com/browser/django/trunk/django/template/context.py>`_
for mapping in self.maps:
for templating is a read-only chain of mappings. It also features
if key in mapping:
pushing and popping of contexts similar to the
mapping[key] = value
:meth:`~collections.ChainMap.new_child` method and the
return
:meth:`~collections.ChainMap.parents` property.
self.maps[0][key] = value
* The `Nested Contexts recipe
def __delitem__(self, key):
<http://code.activestate.com/recipes/577434/>`_ has options to control
for mapping in self.maps:
whether writes and other mutations apply only to the first mapping or to
if key in mapping:
any mapping in the chain.
del mapping[key]
return
* A `greatly simplified read-only version of Chainmap
raise KeyError(key)
<http://code.activestate.com/recipes/305268/>`_.
>>> 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
...
@@ -326,23 +362,23 @@ or subtracting from an empty counter.
...
@@ -326,23 +362,23 @@ or subtracting from an empty counter.
.. seealso::
.. seealso::
* `Counter class <http://code.activestate.com/recipes/576611/>`_
* `Counter class <http://code.activestate.com/recipes/576611/>`_
adapted for Python 2.5 and an early `Bag recipe
adapted for Python 2.5 and an early `Bag recipe
<http://code.activestate.com/recipes/259174/>`_ for Python 2.4.
<http://code.activestate.com/recipes/259174/>`_ for Python 2.4.
* `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
* `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
in Smalltalk.
in Smalltalk.
* Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_.
* Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_.
* `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
* `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
tutorial with examples.
tutorial with examples.
* For mathematical operations on multisets and their use cases, see
* For mathematical operations on multisets and their use cases, see
*Knuth, Donald. The Art of Computer Programming Volume II,
*Knuth, Donald. The Art of Computer Programming Volume II,
Section 4.6.3, Exercise 19*.
Section 4.6.3, Exercise 19*.
* To enumerate all distinct multisets of a given size over a given set of
* To enumerate all distinct multisets of a given size over a given set of
elements, see :func:`itertools.combinations_with_replacement`.
elements, see :func:`itertools.combinations_with_replacement`.
map(Counter, combinations_with_replacement('ABC', 2)) --> AA AB AC BB BC CC
map(Counter, combinations_with_replacement('ABC', 2)) --> AA AB AC BB BC CC
...
@@ -876,14 +912,14 @@ and more efficient to use a simple class declaration:
...
@@ -876,14 +912,14 @@ and more efficient to use a simple class declaration:
.. seealso::
.. seealso::
* `Named tuple recipe <http://code.activestate.com/recipes/500261/>`_
* `Named tuple recipe <http://code.activestate.com/recipes/500261/>`_
adapted for Python 2.4.
adapted for Python 2.4.
* `Recipe for named tuple abstract base class with a metaclass mix-in
* `Recipe for named tuple abstract base class with a metaclass mix-in
<http://code.activestate.com/recipes/577629-namedtupleabc-abstract-base-class-mix-in-for-named/>`_
<http://code.activestate.com/recipes/577629-namedtupleabc-abstract-base-class-mix-in-for-named/>`_
by Jan Kaliszewski. Besides providing an :term:`abstract base class` for
by Jan Kaliszewski. Besides providing an :term:`abstract base class` for
named tuples, it also supports an alternate :term:`metaclass`-based
named tuples, it also supports an alternate :term:`metaclass`-based
constructor that is convenient for use cases where named tuples are being
constructor that is convenient for use cases where named tuples are being
subclassed.
subclassed.
:class:`OrderedDict` objects
:class:`OrderedDict` objects
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment