Decorator and Metaclasses Documentation

Mike C. Fletcher mcfletch at rogers.com
Mon Aug 22 17:57:31 CEST 2005


bruno modulix wrote:

>Mike C. Fletcher wrote:
>(snip)
>  
>
>>Though the don't go into extreme detail on decorators (they are
>>basically syntactic sugar for a particular type of descriptor).
>>
>>    
>>
>Err... Could you elaborate on this ? Decorators are syntactic sugar for
>function wrapping, while descriptors are a 'protocol' to hook into
>attribute lookup, so I don't really see how one can describe the first
>in terms of the second...
>  
>
There are two major types of descriptors, the elven and the dwarven.

    * Elven descriptors are things like property, BasicProperty, VRML97
      fields, Zope Field Properties, or PEAK's mechanisms.  They mediate
      access to an instance's attributes, (both setting and getting of
      values) and are used primarily for domain modeling.
    * Dwarven descriptors are things like staticmethod or classmethod;
      function-like things that tend to look like a function and quack
      like a function, but have some special property or functionality
      attached when accessed as an attribute of a class/instance
      (functions themselves return instance methods or class methods
      depending on how they are retrieved).

As you'll read in the PyCon 2005 paper pointed to, the whole set 
basically grew out of a generalisation of what functions were already 
doing (conceptually).  Functions are, in short, the proto-descriptor.  
That is, objects which control what result is returned by attribute 
access (e.g. an instance or unbound instance method).  Many (most?) 
dwarven descriptors are implemented as simple wrapper functions around 
the base function to use the function's already-present descriptor hooks.

Decorators are syntactic sugar for defining dwarven descriptors.  In 
Python 2.2 and 2.3 a dwarven descriptor was instantiated like this:

    def function( cls ):
        """Do something simple with the class"""
    function = classmethod( function )

in Python 2.4+, they can be instantiated like this:

    @classmethod
    def function( cls ):
        """Do something simple with the class"""

technically you *could* return something that's not a descriptor from 
the decorator (e.g. classmethod), but it's unlikely you'd do that very 
often.

HTH,
Mike

-- 
________________________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com




More information about the Python-list mailing list