[Python-Dev] method decorators (PEP 318) (original) (raw)

Jewett, Jim J jim.jewett at eds.com
Fri Mar 26 11:56:04 EST 2004


Guido (based on discussion with Robert Mollitor and Jim Hugunin) wrote that there are two very different use cases.

We have been discussing transformers, which change how/what the function does. But many uses (such as "release" from the PEP) are true decorators, which are really closer to:

def foo(): pass foo.attr = val

For (2) I am thinking aloud here:

def foobar(self, arg): @author: "Guido van Rossum" @deprecated pass

If I understand, the grammar production would be

'@'+identifier [':' expression]

with expression defaulting to True.

Then

def foobar as [classmethod, synchronized(lock23)] (args):
    @author: "Guido van Rossum"
    @version: (2,3)
    @deprecated
    @variant: @version + (@author,)

    # this next one might be asking for trouble
    @x_starts_as: @x

    @magic_number: random.randint(34) + y
    @version: @version + ("alpha", 1)

    "This is an example function"
    x = 5
    return x

would be equivalent to:

def foobar(args):
    "This is an example function"
    x = 5
    return x

# Evaluate the transforms first, in case they return a 
# different object, which would not have the annotations.
foobar = classmethod(foobar)
foobar = synchronized(lock23)(foobar)

# Now the annotations go on the final object.  Do we
# need to worry about immutable objects, or is that the 
# programmer's own fault?
foobar.author = "Guido van Rossum"
foobar.version = (2,3)

# Default value is True
foobar.deprecated = True

# Do decorators have access to current attributes?
# Did '@' read better than 'self' or 'this'?
foobar.variant = foobar.version + (foobar.author,)

# Does the attribute have access to the local scope?
foobar.x_starts_as = foobar.x

# Do decorators have access to the enclosing scope? 
foobar.magic_number = random.randint(34) + y

# Decorators don't really have to commute, do they?
foobar.version = foobar.version + ("alpha", 1)

-jJ



More information about the Python-Dev mailing list