Are decorators really that different from metaclasses...

Paul Morrow pm_mon at yahoo.com
Fri Aug 27 07:59:39 EDT 2004


Anthony Baxter wrote:
> On Thu, 26 Aug 2004 20:54:22 -0400, Paul Morrow <pm_mon at yahoo.com> wrote:
> 
>>Anthony Baxter wrote:
>>Sure the interpreter uses __getitem__, but you use it too, right?  I
>>mean, you don't need the interpreter to tell you whether instances of
>>the following class can act like a dictionary, do you?
>>
>>    class Foo:
>>       def __getitem__(self, x): pass
> 
> 
> Well, actually, no. The presence or absence of __getitem__ "tells" you nothing.
> It depends on the implementation.
> 
> def __getitem__(self, key): raise AttributeError, '__getitem__'
> 

Oh my.

Following conventions helps readers tremendously. Once a pythonista 
learns a convention, he doesn't spend as long looking at code that 
(appears to) follow that convention.  He *assumes* that the convention 
means the same thing in the code he's reading as it does every else.

Good developers are sensitive to this.  Good developers write code that 
follows conventions.

One convention is that classes whose instances can return values via 
indexing (e.g. foo['x']) define the __getitem__ method.  /Because of 
this convention/, if we create a class that defines the __getitem__ 
method, our readers will expect that instances of that class can return 
values via indexing.

Of course this means that we can have some fun with our readers too.  We 
can create classes that define the __getitem__ method but which raise an 
exception when we try to use the syntax __getitem__ enables [*].  But 
while it may be fun to confuse readers of our code [**], its generally a 
bad idea.

We all know that conventions have meaning.  When we properly use 
conventions in our code, we are telling the reader a little (or in some 
cases a lot) about what is going on in our code, without us having to 
come right out and say it.  This saves us time.  This saves the reader 
time.  This improves the maintainability of our code.

So conventions are good.  And because of that, I propose the following 
as the 20th Zen principle:

     Conventional is better than unconventional.

Paul

* as you did in your example.

** by writing code that follows conventions but doesn't exhibit the 
associated conventional behavior.





More information about the Python-list mailing list