[Python-ideas] Multiple arguments for decorators

Petr Viktorin encukou at gmail.com
Tue Dec 1 07:47:15 EST 2015


On Tue, Dec 1, 2015 at 1:01 PM, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:

>
> I don't know the exact timing here, but I'm willing to bet that at the time that discussion happened:
>
> 1. Python didn't have class decorators yet, and the very notion was seen as obscure and unnecessary.
>
> 2. Inner and nested classes were an unfamiliar feature that almost no other major language supported, rather than being fundamental tools in Java. (Which means nobody had yet had to face the "which self" question, for example.)
>
> 3. Modern functional/OO hybrids like F# and Scala didn't exist (and OCaml was barely known outside specific academic circles), so the only familiar notion of dynamic class creation was the SmallTalk style, rather than functions that return classes (like namedtuple--although its implementation is more Tcl-ish than anything, the interface is still all about using types as first-class values).
>
> So, I'm not sure the objections hold as well today as they did back then. But I'll admit that they're certainly not empty; I'll have to sleep on them, then play with it and see how it really looks.

Metaclasses were probably also obscure.

>
> One more possibility, if property is all we care about, is dedicated syntax. Plenty of other languages have it:
>
>     property x:
>         """x"""
>         def fget(self): return self._x
>         def fset(self, value): self._x = value
>
> I'll bet you could get pretty close to this with MacroPy (and Haoyi has probably already done it for you)...

Indeed, this is quite simple: "property x:" is pretty much syntactic
sugar for "class x(metaclass=property_wrapper)", with a simple
function as the metaclass, as Kevin suggested:

def property_wrapper(name, bases, attrs):
    return property(attrs.get('get'), attrs.get('set'),
attrs.get('del'), attrs.get('__doc__'))

If the syntax was a bit more generic – if "property" would not be a
keyword but the name of a callable – this could solve the "higher
order function accepting multiple distinct functions as inputs"
problem, or "creating something other than a class from a
suite/namespace".


More information about the Python-ideas mailing list