[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:19:39 EST 2017


>
> Attaching to the instance is fine too.  But I prefer the current spelling
> so far:
>
>
> my_menu1 = Menu(['Pizza', 'Cake', 'Pasta'])
>
> my_menu2 = Menu(...)
>
>
> def callback1(self, ...):
>     ...
> def callback2(self, ...):
>     ...
>
> my_menu1.callback = callback2
>
> my_menu2.callback = callback1
>
>
> I don't, it is repeating the variable name three times. I don't see how
> this differs from decorator syntax, do you prefer the old way on that too,
> or am I missing something?
>

I haven't repeated any name.  Notice that '.callback' is different from
'callback1' or 'callback2'.  That's exactly the idea—I can attach
*arbitrary* callbacks later on to the '.callback' attribute.


> I think
>


> you answered yourself here, this would not remove the existing flexible
> way. Just like @decorator syntax didn't remove the more flexible way.
> Honestly this is in my opinion almost one-to-one comparable with decorator
> syntax, and I don't think anyone here dares to claim decorators aren't
> awesome.
>

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/b927e272/attachment.html>


More information about the Python-ideas mailing list