[Python-ideas] of properties and metaclasses

tomer filiba tomerfiliba at gmail.com
Sun Jul 22 23:03:54 CEST 2007


first thing: properties. i prefer this approach to properties (example below).
true, it involves some magic, but the magic is very restricted and contained.

import inspect

def getter(func):
    namespace = inspect.stack()[1][0].f_locals
    p = namespace.get(func.func_name)
    if p is None:
        p = property(func)
    else:
        p = property(func, p.fset, p.fdel)
    return p

def setter(func):
    namespace = inspect.stack()[1][0].f_locals
    p = namespace.get(func.func_name)
    if p is None:
        p = property(None, func)
    else:
        p = property(p.fget, func, p.fdel)
    return p

class File(object):
    def __init__(self):
        self._pos = 8

    @getter
    def position(self):
        return self._pos

    @setter
    def position(self, value):
        self._pos = value


f = File()
print f.position
f.position = 11
print f.position
==============================================

btw, in py3k, with class decorators, you could instead use
class File:
     @propertyclass
     class position:
         def get(self):
             return self.tell()
          def set(self):
              return self.tell()
==============================================

second -- metaclasses. there's some notion (Josiah et al) that metaclasses
were introduced to make classes behave as generic attribute containers. this
is not true. using metaclasses like so was not the original intent.

metaclasses are the types of types. they also happened to be executed
before the class body is made into a class, which means they can be used
to tweak class creation, but that's a technicality. using this feature to turn
classes into anything you want is wrong: it's implicit, complex, and mostly
unreadable by the common programmer. i'd guess 80% of python
programmers have never used metaclasses. it's a difficult concept,
and should be used sparsely.

class decorators would cover ~70% of the use-cases for metaclasses,
but for some reason, people insist on complicating even more the
metaclass machinery in py3k. see my protest [1], which was silently ignored.

what you people are asking for is a new language construct which allows
the definition of syntactic namespaces. much like the deceased make pep.
(mis)using classes for this purpose is wrong. it's different -- it's
not a class
anymore. so why is it being defined by a class-clause?

@property
namespace foo:
    def get(self):
        ....
    def set(self):
        ....


-tomer

[1] http://mail.python.org/pipermail/python-3000/2007-June/008330.html



More information about the Python-ideas mailing list