[Python-ideas] Multiple arguments for decorators

Guido van Rossum guido at python.org
Tue Dec 1 11:22:30 EST 2015


On the other hand, if we're willing to put up with some ugliness in the
*implementation*, the *notation* can be fairly clean (and avoid the
creation of a class object):

class Example:
    def __init__(self):
        self._x = 0.0
        self._y = 0.0

    class x(Property):
        def get(self):
            return self._x
        def set(self, value):
            self._x = float(value)

    class y(Property):
        def get(self):
            return self._y
        def set(self, value):
            self._y = float(value)

Notice there's no explicit mention of metaclasses here. The magic is that
Property is a class with a custom metaclass. The implementation could be as
simple as this:

class MetaProperty(type):
    """Metaclass for Property below."""

    def __new__(cls, name, bases, attrs):
        if name == 'Property' and attrs['__module__'] == cls.__module__:
            # Defining the 'Property' class.
            return super().__new__(cls, name, bases, attrs)
        else:
            # Creating a property.  Avoid creating a class at all.
            # Return a property instance.
            assert bases == (Property,)
            return property(attrs.get('get'), attrs.get('set'),
                            attrs.get('delete'), attrs.get('__doc__'))


class Property(metaclass=MetaProperty):
    """Inherit from this to define a read-write property."""

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151201/778105e1/attachment.html>


More information about the Python-ideas mailing list