Nested Mapping

Raymond Hettinger python at rcn.com
Thu Oct 21 21:06:00 EDT 2010


On Oct 21, 5:18 pm, Paul Rubin <no.em... at nospam.invalid> wrote:
> The API you suggested looks reasonable although you should also say how
> to delete a context, how to find the inner contexts of a context, etc.

The c.parent.parent.parent chain finds successive enclosing contexts:

   while c.parent is not None:
       print c
       c = c.parent


> One question: what should
>
>    c["foo"] = 7
>    d = c.new_child()
>    del d["foo"]
>
> do?  

By default, it raises a KeyError because 'foo' is not in the current
context.

But if enable_nonlocal is set to True, it removes 'foo' from the
parent context, c.

Depends on whether you want parent contexts to be mutable or not.
With Python's nonlocal keyword, we can set values in an enclosing
scope.  This tool lets you do that also.


Raymond




More information about the Python-list mailing list