[Python-ideas] Multiple arguments for decorators

Kevin Modzelewski kmod at dropbox.com
Mon Nov 30 22:21:57 EST 2015


Class scopes definitely feel like a good match -- they are a way of saying
"evaluate all of these expression, pass the resulting locals to a custom
function, and bind the result of that function to the classname".  Usually
the function is type(), which constructs a new class, but by setting a
custom metaclass we can avoid creating a class just to wrap the scope:

class PropertyMetaclass(type):
    def __new__(cls, name, bases, attrs):
        return property(attrs.get('get'), attrs.get('set'),
attrs.get('del'), attrs.get('__doc__'))

class Foo(object):
    class myprop(metaclass=PropertyMetaclass):
        def get(self):
            return 1
        def set(self, v):
            pass
        __doc__ = 1

f = Foo()
print(f.myprop)


The "class myprop(metaclass=PropertyClass)" line is pretty ugly though.

On Mon, Nov 30, 2015 at 6:41 PM, David Mertz <mertz at gnosis.cx> wrote:

> On Mon, Nov 30, 2015 at 6:14 PM, Chris Angelico <rosuav at gmail.com> wrote:
>
>> def call(func):
>>     def inner(cls):
>>         return func(**{k:v for k,v in cls.__dict__.items() if not
>> k.startswith('_')})
>>     return inner
>>
>> class Foo:
>>     def __init__(self):
>>         self._x = 42
>>     @call(property)
>>     class x:
>>         def fget(self):
>>             return self._x
>>         def fset(self, value):
>>             self._x = value
>>         def fdel(self):
>>             del self._x
>>
>
> I think this looks perfectly nice, actually.  I was just trying to work
> out almost the same thing but using a `def x()` rather than `class f` as
> the nesting construct.  I think Chris' is better though.  I think I might
> want to define something like:
>
> make_property = call(property)
>
> class Foo:
>     def __init__(self):
>         self._x = 42
>     @make_property
>     class x:
>         def fget(self):
>             return self._x
>         def fset(self, value):
>             self._x = value
>         def fdel(self):
>             del self._x
>
>
>
> --
> Keeping medicines from the bloodstreams of the sick; food
> from the bellies of the hungry; books from the hands of the
> uneducated; technology from the underdeveloped; and putting
> advocates of freedom in prisons.  Intellectual property is
> to the 21st century what the slave trade was to the 16th.
>
> _______________________________________________
> 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/20151130/cef752ab/attachment-0001.html>


More information about the Python-ideas mailing list