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

Steven D'Aprano steve at pearwood.info
Fri Feb 10 05:13:27 EST 2017

On Fri, Feb 10, 2017 at 11:13:47AM +0200, Markus Meskanen wrote:
> 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

That saves one line, at the cost of introducing even more complexity to 
the language.

Are these use-cases common enough to justify the extra syntax?

> 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):

That's just putting arbitrary symbols into the statement.

I know that *ultimately* all symbols are arbitrary, but . dot means 
attribute access in Python, so Foo.foo at least has some connection to 
creating an attribute of Foo called foo. In what way does "Foo greater 
than foo" suggest to the reader that foo ends up as an attribute of Foo?

> 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.):

I'm sure that there are a number of use-cases for injecting a method 
into an existing class. But we already have a way of doing that:

def method(self): ...
Spam.method = method

What advantage does this proposed syntax have?

Since that's not actually a rhetorical question, I'll answer it myself:

def Spam.method(self) not only saves the line

    Spam.method = method

but it also avoids leaving a global name "method" in the namespace (no 
need to follow with `del method`); it makes it explicit from the 
beginning that the function is an attribute of Spam.

If the implementation is clever enough, it can avoid clashing with a 
global of the same name:

eggs = "something"

def Spam.eggs(self):

def Cheese.eggs(self):

assert eggs == "something"

So the idea isn't without merit; but the question in my mind is whether 
the advantages outweigh the extra complexity.


More information about the Python-ideas mailing list