[Python-Dev] Decorators after 'def' should be reconsidered

barnesc at engr.orst.edu barnesc at engr.orst.edu
Wed Aug 11 01:12:58 CEST 2004


>In the discussion on decorators months ago, solutions involving
>special syntax inside the block were ruled out early on.  Basically,
>you shouldn't have to peek inside the block to find out important
>external properties of the function.

>--Guido van Rossum (home page: http://www.python.org/~guido/)

I disagree.

The most important part of a function is the first def line.

If you place other stuff before the def line, you make it
harder to grep for the def line.


Compare:

-----------------------------------------------
Option A
-----------------------------------------------

"""
Hi,

Performs a binary operation.

Docstring.
"""
@staticmethod
@synchronized(lockvar)
def f(a, b):
    return a + b

"""
Now,

Performs a simple operation.
"""
@classmethod
def g(a):
    return a

-----------------------------------------------
Option B
-----------------------------------------------

def f(a, b):
    @staticmethod
    @synchronized(lockvar)
    """
    Hi,

    Performs a binary operation.

    Docstring.
    """
    return a + b

def g(a):
    @classmethod
    """
    Now,

    Performs a simple operation.
    """
    return a


Now, forget everything you've learned about Python.
Forget that @ symbols are ugly.

 - For which method is it visually easier to find the function def?

 - For which method is the code in the most logical order?

Note that Option A causes you to skim all the way through
the docstring and the decorators to find out which function
is being defined.  At this point, you have to start over
at the docstring, to find out what the function actually does.

Option A is especially painful when a large number of functions
are thrown into a module.  It is almost impossible to grep
efficiently for the function names.  Thus the code appears
disorganized, and messy.

It seems strange that Option B was "ruled out early on."
Option B is clearly more readable.

 - Connelly


More information about the Python-Dev mailing list