[Python-ideas] Define a method or function attribute outside of a class with the dot operator

Markus Meskanen markusmeskanen at gmail.com
Fri Feb 10 04:13:47 EST 2017


I'm suggesting the addition of support to using a dot notation when
defining a function to be a method of a class, or a callback attribute. For
example:

    def foo(self):
        pass
    Foo.foo = foo

Becomes:

    def Foo.foo(self):
        pass

Other syntaxes can also be used if the dot itself is an issue, although I
dislike these:

    def Foo:foo(self):
    def foo at Foo(self):
    def Foo>foo(self):
    def Foo&foo(self):

This functionality would be useful in the few rare cases where the class
itself needs to be accessed in the function's definition (decorator,
typing, etc.):

    @barify(Foo)
    def Foo.method(self, other: Foo) -> Foo:
        pass

And when an object needs a callback as an attribute:

    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([item1, item2])

    def my_menu.select_callback(self, item_index):
        print(self.items[item_index])

As opposed to:

    my_menu = Menu([item1, item2])

    def select_callback(self, item_index):
        print(self.items[item_index])
    my_menu.select_callback = select_callback

Or defining them in "unnatural" order:

    def select_callback(self, item_index):
        print(self.items[item_index])

    my_menu = Menu([item1, item2], select_callback)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170210/00e6a261/attachment.html>


More information about the Python-ideas mailing list