Problem of Readability of Python

Steven Bethard steven.bethard at gmail.com
Sun Oct 7 23:41:18 EDT 2007


Alex Martelli wrote:
> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
>> class Record(object):
>>     __slots__ = ["x", "y", "z"]
>>
>> has a couple of major advantages over:
>>
>> class Record(object):
>>     pass
>>
>> aside from the micro-optimization that classes using __slots__ are faster
>> and smaller than classes with __dict__.
>>
>> (1) The field names are explicit and self-documenting;
>> (2) You can't accidentally assign to a mistyped field name without Python
>> letting you know immediately.
[snip]
> If I had any real need for such things, I'd probably use a metaclass (or
> class decorator) to also add a nice __repr__ function, etc...

Yep.  That's what the recipe I posted [1] does. Given a class like::

     class C(Record):
         __slots__ = 'x', 'y', 'z'

it adds the most obvious __init__ and __repr__ methods. Raymond's 
NamedTuple recipe [2] has a similar effect, though the API is different.

[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
[2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261

STeVe



More information about the Python-list mailing list