__metaclass__ and __author__ are already decorators

Andrew Durdin adurdin at gmail.com
Sat Aug 21 17:24:18 CEST 2004


On Sat, 21 Aug 2004 10:38:01 -0400, Paul Morrow <pm_mon at yahoo.com> wrote:
> Thinking about decorators, and looking at what we are already doing in
> our Python code, it seems that __metaclass__, __author__, __version__,
> etc. are all examples of decorators.  So we already have a decorator
> syntax.  What is the compelling reason to invent a new one?  And if we
> do, what's to become of the old one?

__author__ and __version in a class (as per your example) are setting
class attributes, not "decorating" the class anymore than the def's
that declare instance methods are.
Within a function, __author__ and __version__ are local variables, and
nothing more; specifically, assigning to them does *not* set function
attributes:

  >>> def foo():
  ...     __author__ = "me"
  ...     return 5
  ...
  >>> print foo.__author__
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  AttributeError: 'function' object has no attribute '__author__'
  >>> print foo.func_code.co_varnames
  ('__author__',)

__metaclass__ on the other hand is a magic attribute. I haven't worked
out the details, but I have the feeling that what a metaclass does to
a class is not replicable merely by decorating the class; in other
words, that:

  class Foo:
      __metaclass__ = Bar

is *not* equivalent to

  class Foo:
      pass

  Foo = Baz(Foo)

for any definitions of Bar and Baz. This is just my intuition, however.



More information about the Python-list mailing list