[Python-ideas] Fwd: Define a method or function attributeoutsideof a class with the dot operator
Markus Meskanen
markusmeskanen at gmail.com
Sun Feb 12 11:51:25 EST 2017
I will say, though, that you're right that we've over-reacted a bit to
the monkeypatching use case. Although maybe that's because no-one can
think of many *other* use cases that they'd need the new syntax for
:-)
Paul
Hi Paul, I believe at least two other use cases than monkey patching have
been mentioned already:
1. Allowing the class to be used in the method's header, f.e. for typing
and decorators:
@decorate(MyClass)
def MyClass.method(self, other: MyClass) -> List[MyClass]:
...
This is useful since you can't refer the class itself inside of its body.
At the moment the way to use typing is to write the class's name as a
string... It feels awful.
2. To register callbacks to objects, i.e. plain out set an attribute for an
instance. I've used the menu example above:
class Menu:
def __init__(self, items=None, select_callback=None):
self.items = items if items is not None else []
self.select_callback = select_callback
my_menu = Menu(['Pizza', 'Cake', 'Pasta'])
def my_menu.select_callback(item_index):
if item_index == 0: # Pizza
serve_food(pizza)
else: # Cake or Pasta
...
This is just one example of using it to set an instance's variable to a
callback. It's just shorthand for:
def select_callback(item_index):
...
my_menu.select_callback = select_callback
This reads much easier and saves us from typing the same thing three times
(see decorators).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170212/650f6cc4/attachment.html>
More information about the Python-ideas
mailing list