[Python-ideas] Ordered storage of keyword arguments

spir denis.spir at gmail.com
Sat Oct 30 11:02:51 CEST 2010


On Fri, 29 Oct 2010 14:19:33 -1000
"Carl M. Johnson" <cmjohnson.mailinglist at gmail.com> wrote:

> Thinking about it a little more, if I were making an HTML tree type
> metaclass though, I wouldn't want to use an OrderedDict anyway, since
> it can't have duplicate elements, and I would want the interface to be
> something like:
> 
> class body(Tree()):
>     h1 = "Hello World!"
>     p  = "Lorem ipsum."
>     p  = "Dulce et decorum est."
>     class div(Tree(id="content")):
>         p = "Main thing"
>     class div(Tree(id="footer")):
>         p = "(C) 2010"
> 
> So, I'd probably end up making my own custom kind of dict that didn't
> overwrite repeated names.

Ah, but that's a completely different issue. You seem to be talking of an appropriate data structure to represent (the equivalent of) a parse tree, or rather an AST. In most grammars there are sequence patterns representing composite data, such as funcDef:(parameterList block) in which (1) order is not meaningful (2) most often each "kind" of element happens only once (*). And there are repetitive patterns, such as block:statement*, in which elements "kinds" also repeat.
Composite elements like func defs can be represented as dicts (ordered or not), but actually their meaning is of a "flexible record", a named tuple (**). It's _not_ a collection. The point is they can be indexed by "kind" (id est which patterns generated them).
Repetitive elements do not have this nice property, they must be represented as sequences of elements _holding_ their kind. For this reason, tree nodes often hold the element "kind" in addition to their actual data and some metadata.


Denis

(*) But that's not always true, eg addition:(addOperand '+' addOperand).

(**) I miss "free objects" in python for this reason -- people often use dicts instead. I'd like to be able to write: "return (color:c, position:p)", where the defined object is instance of Object directly, or maybe of Individual, meaning Object with a __dict__.
class Individual:
    def __init__ (self, **slots):
        self.__dict__ = slots
    def __repr__(self):
        return "(%s)" % \
            ' '.join("%s:%s" %(k,v) for (k,v) in self.__dict__.items())
print Individual(a=135, d=100)  # (a:135 d:100)
If only we had a literal notation for that :-) No more need of classes for singletons.
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com




More information about the Python-ideas mailing list