A class for C-like structuures in Python

Alex Martelli alex at magenta.com
Wed Aug 9 03:53:18 EDT 2000


"Thomas Gagne" <tgagne at ix.netcom.com> wrote in message
news:3990CD96.ADF0A0D8 at ix.netcom.com...
> OK.  So they really aren't C structures, but they're close.
>
> Now, I've only been programming in Python for about two days, so naturally
I'm
> an expert.

Isn't this a truly wonderful language?  It DOES have this effect -- of
giving one
the self-assurance that things work as sensibly expected.

One little modification I would suggest...:

> def getMember(self, name):
> if (self.members.has_key(name)):
> return self.members[name]
>
> def setMember(self, name, value):
> if (self.members.has_key(name)):
> self.members[name] = value;
> return self.members[name]

If you give these the special names __getattr__ and __setattr_, you
can then use a simpler syntax for access -- i.e.:

    def __checkname(self,name):
        if not self.members.has_key(name):
            raise AttributeError,"No struct-field is named "+name
    def __getattr__(self,name):
        self.__checkname(name)
        return self.members[name]
    def __setattr__(self,name,value):
        self.__checkname(name)
        self.members[name]=value

I've also slightly polished the syntax (no need for C-like extra
parentheses on if conditions, or ';' at statement end) and made
semantics closer to Python specs (raise AttributeError, if the
attribute is not found; __setattr__ returns None).  But this is
minor.  The gain is mostly in changing:
> self.setMember('len', 0)
> self.setMember('sequence', 0)
> self.setMember('reply', 0)
to
self.len=self.sequence=self.reply=0

or, of course, you can do it in 3 lines, but it's still clearer:
    self.len=0
    self.sequence=0
    self.reply=0


It would also be possible (but this is a matter of performance, and
not a very important one) to optimize asBytes, if it's called often,
into a single statement:

    def asBytes(self):
        return apply(struct.pack,[self.fmt]+self.members.values())

basically letting the written-in-optimized-C Python runtime/builtins
do the looping, rather than doing it yourself in Python code.  But
I guess your chosen form may be clearer/more explicit, perhaps!


Anyway -- good work!


Alex






More information about the Python-list mailing list