empty classes as c structs?

Carlos Ribeiro carribeiro at gmail.com
Sat Feb 5 16:27:45 EST 2005


On Sat, 05 Feb 2005 12:05:13 -0700, Steven Bethard
<steven.bethard at gmail.com> wrote:
> The type suggested in this PEP also allows a simple means of
> representing hierarchical data that allows attribute-style access::
> 
>      >>> x = Bunch(spam=Bunch(rabbit=1, badger=[2, 3, 4]), ham='neewom')
>      >>> x.spam.badger
>      [2, 3, 4]
>      >>> x.ham
>      'neewom'

Static nested data structures are particularly tricky to declare in
Python. Your example works, but IMHO it's rather a workaround than a
real solution. Other languages (such as Delphi) have a record type
that can be nested naturally. Nested classes in Python don't work the
same as Delphi records; on instantiaton, only the outer (parent) class
is instantiated, and the nested (children) classes stay as classes.
This can lead to subtle bugs as class attribute acesses are mixed with
instance attribute accesses with unpredictable results. I have tried
to deal with these problems on MetaTemplate, a library for
declarative-style code in Python. You can see some ideas on this page:

    http://metatemplate.python-hosting.com/wiki/MetaTemplate

One of my goals was to model nested data structures as nested classes
in Python. My solution to the nesting problem involves some
autoinstantiation magic which breaks traditional semantics, but works
for the particular application ('practicality beats purity').

I'm interested to see where this will lead us. Other related problems
are named tuples, and ordered attribute access. I deal with the later
in MetaTemplate, but the former is out of scope for the library. In
the long term, I wish Python grows a true record type. The semantic
differences between records and classes are enough to justify it in my
opinion.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list