empty classes as c structs?

Steven Bethard steven.bethard at gmail.com
Sun Feb 6 17:43:04 EST 2005


Alex Martelli wrote:
> Steven Bethard <steven.bethard at gmail.com> wrote:
>>I don't know what the right solution is here...  I wonder if I should
>>write a classmethod-style descriptor that disallows the calling of a 
>>function from an instance?  Or maybe I should just document that the 
>>classmethods should only be called from the class?  Hmm...
> 
> 
> Another approach is to add a few "reserved words" to the ones Python
> itself would reject in the initialization.  Just you cannot do:
> 
>     b = Bunch(continue=23)
> 
> you may choose to forbid using getDict=42 - if you do that you probably
> want to forbid any magicname too, since e.g.
> 
>     b = Bunch(__dict__=99)
> 
> can't work ``right'' no matter what, while setting e.g. __deepcopy__
> similarly might confuse any copy.deepcopy(b), etc, etc.

Yeah, I thought about this.  I certainly don't have any problem with 
disallowing magic names.  For other names, I'm less certain...

>>How do you feel about getDict and setDict also being classmethods?
> 
> Uh?  I want to get or set the dict of a specific instance -- not those
> of the whole class.  How would you design them as classmethods...?

The classmethod would have to be called with an instance, e.g.:

class Bunch(object):
     @classmethod
     def getDict(cls, self):
         return self.__dict__

     @classmethod
     def setDict(cls, self, dct):
         self.__dict__ = dct

Of course, these could be staticmethods instead since they don't need 
the class, but the point is that you should be calling them like:

     adict = Bunch.getDict(bunch)

or

     Bunch.setDict(bunch, adict)

The complications with attribute hiding is one of main reasons I've 
tried to minimize the number of methods associated with Bunch...

Steve



More information about the Python-list mailing list