Are decorators really that different from metaclasses...

Paul Morrow pm_mon at yahoo.com
Thu Aug 26 07:28:32 EDT 2004


Anthony Baxter wrote:
> On Wed, 25 Aug 2004 19:47:35 -0400, Paul Morrow <pm_mon at yahoo.com> wrote:
> 
>>What you're trying to illustrate (I believe) is a superclass doing
>>something based on the docstring of a subclass.  Yes this certainly does
>>happen.  But the superclass and subclass are separate objects.  I was
>>talking about the situation where a function does something based on
>>/its own/ metadata.  That is what I'm saying virtually never happens,
>>and therefore it's ok to make all assignments to __xxx__ attributes
>>inside of a function def create /function attributes/ rather than /local
>>variables/.
> 
> 
> This is an extraordinarily complex idea - you're proposing that inside
> a function there is now access to a brand new namespace, that of the
> function object itself. I don't think you appreciate just _how_ much
> work this would requre, nor the complexity of trying to explain this
> to users. Remember, at the moment, you can't even get access to the
> function object itself from inside the function, without using a hack
> like sys._getframe() or raising an exception.
> 

No I'm not suggesting that.  The function would continue to have exactly 
the same namespace.

This is not a big change; quite the contrary...

The interpreter, when it is executing a def statement, after it binds 
__doc__ to the docstring, would execute any assignments to __xxx__ 
attributes it finds immediately following the docstring (if present).  So

    def circumference(diameter):
        """ This is a docstring. """
        __author__ = 'Paul Morrow'
        pi = 3.14
        return pi * diameter

would be /exactly equivalent/ to

    def circumference(diameter):
        pi = 3.14
        return pi * diameter

    circumference.__doc__ =  """ This is a docstring. """
    circumference.__author__ = 'Paul Morrow'


See how simple?  In fact, isn't this just as simple --- or even simpler 
-- than what would be require to implement J2 or A1?

And remember, the assumption here is that these assignments (to __xxx__ 
attributes) are a form of declarations /about the function/, just as 
docstrings are now.  There's no need to support conditional declarations...

    def foo():
       """ I am a docstring. """
       __author__ = 'Morrow'

       # Just as there is no proper, 'definition time' way to
       # conditionally change a docstring, the code below
       # will generate an exception (at runtime).
       if 1:
          __version__ = '0.1'
       else:
          __version__ = '0.2'

Think of what I'm proposing here as just a convenience syntax.  We can 
already do the same thing after (outsidef of) the function def as the 
second circumference example above shows.

Paul




More information about the Python-list mailing list