Easy "here documents" ??

Bengt Richter bokr at oz.net
Mon Dec 20 03:58:24 CET 2004


On Sun, 19 Dec 2004 16:46:34 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>Jerry Sievers wrote:
>
>> It gets uglier though if you want to do this from inside a function
>> and have variables from more than one scope interpolated.  For that
>> you need something that can treat a series of dicts as one.If there's
>> built in functionality in Python for this, I haven't discovered it
>> yet.
>
>you use them all the time: plain old instance objects...
>
>here's a rather horrid piece of code that turns a list of dictionaries
>into a single object the automatically searches the dictionary chain
>when you ask for attributes (use getattr for non-standard keys).
>
>def flatten_dicts(*dicts):
>    root = None
>    for dict in dicts:
>        class wrapper: pass
>        if root:
>            wrapper.__bases__ = (root,)
>        wrapper.__dict__ = dict
>        root = wrapper
>    return wrapper()
>
>obj = flatten_dicts(d1, d2, d3)
>
That's one I hadn't thought of in any form, but I'm glad to have been
shown the opening (although I am bit surprised at such dark side stuff
from you, even with the "horrid piece of code" qualification ;-)

Seriously, has anyone done a definitive documentation of
all the namespaces (incl name-search paths and r/w rules) of Python?
ISTM the name access games are a bit irregular. The difficulty of creating
a mapping usable like

    txt = 'bim bam %(boo)s' % mapping

that will do _exactly_ the same thing as

    txt = 'bim bam %s' % (boo,)

no matter whether boo is local, global, or a closure cell is symptomatic, ISTM.
flattendicts(locals(), globals()) is close, but not quite there due to locals()'s
being only a snapshot and leaving out closure cells -- is the latter intentional BTW?
ISTM closure cell variables belong somewhere, and it can't be in globals().

If every local context had a magic __localnamespace__ object so that

   assert __localnamespace__.x is x and __localnamespace__['x'] is x

never failed in any local context except with NameError, you could do lots
of things easily. Might not be so easy to implement though. But with __getattr__
and __getitem__ doing the same access,

    txt = 'bim bam %(boo)s' % __localnamespace__

would do what one might like. A sys._getframe(depth).f_localnamespace
frame attribute as a way of peeking into various local namespaces via their
__localnamespace__ objects might make name-chasing easier and more regular
there too. Just a thought, not thought out ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list