A class for C-like structuures in Python

Alex Martelli alex at magenta.com
Wed Aug 9 17:33:02 EDT 2000


"Thomas Gagne" <tgagne at ix.netcom.com> wrote in message
news:3991839F.B5783118 at ix.netcom.com...
    [snip]
> I think there's a problem mixing __dict__ with standard variable
definitions.

Just more confusion on my part -- and I reiterate my apologies.  Definitely
a bad day for me; sorry.


> Whether I use __dict__['fmt'] = '' or the simpler self.fmt = '' I get the
same
> result (above)

Yes, but it's not where you're first setting fmt that you get it (if you
set it indirectly via __dict__); it is, rather, at:

>    self.fmt = self.fmt + f

Here you're setting it directly, so __setattr__ gets called.  Not
__getattr__,
because fmt IS in the __dict__ at this point; but __setattr__ does NOT get
bypassed this way -- it always gets a say on whether a change is OK.

So, you either always use self.__dict__['fmt']=self.fmt+f, or modify
the __setattr__ to treat specially those few fields you DO want to
have in the __dict__ itself, e.g.:

class CStructure:
    def __init__(self, theTuples):
        self.__dict__['members'] = {}
        self.__dict__['fmt'] = ''
        self.__dict__['shape'] = theTuples
        for n,f in self.shape:
            self.members[n] = None
            self.fmt = self.fmt + f
    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):
        if self.__dict__.has_key(name):
            self.__dict__[name]=value
        else:
            self.__checkname(name)
            self.members[name]=value

All in all, I guess the modest syntax sugar of being able to
refer to x.foo rather than x.members['foo'] may not be worth
this bother, as you suggest in a later post.  And should you
ever want to have a real structure-field named members, or
fmt, or shape, this approach would be bad news.


Alex






More information about the Python-list mailing list