[Python-ideas] Multiple arguments for decorators
Emanuel Barry
vgr255 at live.ca
Tue Dec 1 18:00:52 EST 2015
I actually like this approach better than a syntactic way. The only downside is that custom decorators don't get this addition, but then the recipe can be used and re-used for those cases. +1
Thanks everyone who replied and offered their solutions, I appreciate it :)
From: guido at python.org
Date: Tue, 1 Dec 2015 08:22:30 -0800
To: abarnert at yahoo.com
Subject: Re: [Python-ideas] Multiple arguments for decorators
CC: python-ideas at python.org
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)
_______________________________________________
Python-ideas mailing list
Python-ideas at python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151201/6f441d0d/attachment.html>
More information about the Python-ideas
mailing list