Implementing ChainMap

ChainMap is a dictionary-like class, used to create a single view of multiple mappings. It allows for quick linking between multiple mappings so they can all be considered as a single unit, which is useful when simulating nested scopes and when templating. This can be faster than creating a new dictionary and running update() calls repeatedly.

The command to create a ChainMap is as follows:

collections.ChainMap(*maps)

As usual, the *maps is simply a number of dictionaries or other map objects passed in to be combined into a single, updateable view. If no mappings are passed in, then an empty dictionary is created so the new chain has at least one mapping available to it.

The mappings themselves are contained, behind the scenes, within a list. The list is a public object and it can be accessed or updated via the maps attribute. When looking for a key, the search occurs over the mapping list until the key is found. However, modifications to the list occur only on the first mapping.

To keep memory requirements low, ChainMap doesn't make a copy of all the mappings, but simply uses the mappings via reference. Thus, if an underlying mapping is modified, it is immediately available to the ChainMap object.

All normal dictionary methods are available, as well as the following special ChainMap methods:

  • maps: It is referred to earlier; this is a user-accessible list of mappings. The list is based on search order, that is, first-searched-to-last-searched. This list can be modified to change the mappings that are searched.
  • new_child(m=None): It returns a new ChainMap that has a new map, followed by all the maps of the current instance. If a value for m is passed in, it becomes the first map at the front of the list. If not provided, an empty dictionary is used. This method can be used to create subcontexts that can be updated without modifying parent mapping values.
  • parents: It returns a new ChainMap that holds all the maps in the current instance except for the first one. This is useful to skip the first map when searching.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset