[Python-ideas] Fwd: Define a method or function attributeoutsideof a class with the dot operator
David Mertz
mertz at gnosis.cx
Sun Feb 12 13:26:13 EST 2017
Oh, I probably want `return fn` inside my inner decorator. Otherwise, the
defined name gets bound to None in the global scope. I'm not sure, maybe
that's better... but most likely we should leave the name for other users.
I just wrote it without testing.
On Sun, Feb 12, 2017 at 10:19 AM, David Mertz <mertz at gnosis.cx> wrote:
>
> But we already *have* decorators! Here's a nice factory for them:
>
> def attach_to(thing, name=None):
>
> def decorator(fn):
>
> if name is None:
>
> name = fn.__name__
>
> setattr(thing, name, fn)
>
> return decorator
>
>
> This does everything you are asking for, e.g.:
>
> my_menu = Menu()
>
> @attach_to(my_menu)
> def callback(self, ...)
> ...
>
>
> I got extra fancy with two lines to allow you to either use the same name
> as the function itself or pick a custom name for the attribute.
>
--
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170212/41a8fa5d/attachment-0001.html>
More information about the Python-ideas
mailing list