Data attributes...

Alex Martelli aleax at aleax.it
Fri Jan 25 08:51:56 EST 2002


"Joseph A Knapka" <jknapka at earthlink.net> wrote in message
news:3C4FF8F4.E6B26790 at earthlink.net...
    ...
> more you'll appreciate it. For example, I have an application
> that parses a file and produces a syntax tree made up of
> objects of class SyntaxNode. Later I wanted to be able to
> graphically display the syntax tree. In C++, I would have
> had to either diddle the SyntaxNode class to add GUI data
> that the parser would never use, or else create a new
> class for GUISyntaxNodes that either derived from SyntaxNode
> and added the appropriate data, or else kept a reference to
> the associated SyntaxNode, and copy the entire SyntaxNode tree
> into a tree of GUISyntaxNodes for the UI's benefit. But in Python,

Or build a "std::map<SyntaxNode, GUIStuff> wow;" and put in
wow[whatever].pleek what in Python you can put directly in
whatever.pleek.  Not THAT big a deal, although not quite as
slick as being able to put data directly in the existing
nodes -- you have to pass around object wow as well as the
tree, but that's not too bad.

BTW, this technique is also important in Python.  I believe
the docs for module weakref mention it specifically, although
with the idea of using a Python weakly-referencing-dict and not
a C++ std::map of course (indeed the problem of 'what to do
about the map entry if a node is destroyed' is one of the issues
with the C++ approach, while Python's weakrefs solve it cleanly).

Sometimes you cannot add attributes to certain things (they
may be instances of types rather than classes, or instances
of new-style 2.2 classes defining __slots__, or...) and for
such cases keeping weakref in mind can help

OTOH, putting an object's attributes right in the object IS
simplest and clearest when applicable -- that's why function
objects gained the ability to have arbitrary attributes in
Python 2.1, for example.


Alex






More information about the Python-list mailing list