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

Steven D'Aprano steve at pearwood.info
Wed Feb 15 06:43:12 EST 2017

On Mon, Feb 13, 2017 at 06:14:34PM -0800, David Mertz wrote:
> On Mon, Feb 13, 2017 at 5:48 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> > # the clean proposed way:
> > def instance.method(self):  # or MyClass.method
> >     ...
> >
> > But I don't think that we can reasonably argue that the suggested syntax
> > isn't a clear, non-trivial win over the status quo, not unless we're
> > also going to argue that introducing decorator syntax was a waste of
> > time.
> >
> I argue it's not a win specifically because we HAVE decorators already.

I wouldn't word it quite like that, but I'll certainly agree that a 
decorator may be able to (almost) solve the method-injection use-case. 
Being able to write:

def method ...

is almost as nice as 

def Class.method ...

The one thing a decorator can't do is clean up after itself and avoid 
leaving an unneeded and unnecessary 'method' name in the current 

> Moreover, I think your spelling of what it is sugar for is slightly off.
> The `del method` at the end feels wrong to me.  Specifically, in the
> example I repeated of attaching callbacks, the reason I'd want a function
> defined outside any particular class (or instance) scope is because I might
> want to use the same function as a method of various classes.

The existing syntax won't be going away, so anything you can do now, you 
will still be able to do :-)

My gut feeling is that `def Class.method` should avoid polluting the 
current namespace. If you need access to the method again, you can 
always grab it from `Class.method`.


More information about the Python-ideas mailing list