[Python-Dev] Multiple dicts for string interpolation?

Skip Montanaro skip@mojam.com (Skip Montanaro)
Tue, 25 Jan 2000 22:38:53 -0600 (CST)


    >> I'd like to propose a third alternative.  How about if the string
    >> interpolation function accepted a tuple of dictionaries directly:
    >> 
    >> s = format % (d1, d2)

    Guido> Gut feeling: it's dangerous to fill up every possible dark corner
    Guido> with specific semantics that are occasionally useful, because if
    Guido> you go too far you lose useful redundancy, and you end up with
    Guido> Perl.

Yeah, I am kind of taking advantage of the fact that the format operator
doesn't happen to use tuples of dicts already, though this seems like a
natural extension of the current semantics.   Currently, you can have

    Style of                Simple form     Complex form
    Interpolation
    -------                 -----------     ------------
    sprintf                 string          tuple of strings
    named                   dict            tuple of dicts

It does complicate the decision making process in the string format routine
a bit.

    Guido> I think it depends on to what extent this is a common, useful
    Guido> idiom.  Do you have evidence of that?  Examples?

Well, the first place I ran into it was in DocumentTemplates a few years
ago.  They used an idiom heavily which may have now been replaced by
acquisition where you'd effectively push and pop value dicts onto a stack as
you entered and exited nested blocks of DTML code.  Their solution was a
special dict-like object.

The example that made the light click for me this evening was having an
object whose class dict stores constants and whose instant dict stores
varying values.  It seemed cleaner to me to do

    obj = Class()
    ...
    s = format % (Class.__dict__, obj.__dict__)

than go through the intermediate step of building a separate dict which
would just get discarded as soon as this bit of string building was
complete.  (I will perform this once for each of several thousand
instances.)

It's not a big deal.  If it seems too obscure the other obvious solutions
are not gruesome.

Skip