[Python-ideas] Fwd: Define a method or function attributeoutsideof a class with the dot operator

Steven D'Aprano steve at pearwood.info
Mon Feb 13 19:44:14 EST 2017

On Mon, Feb 13, 2017 at 11:50:09AM -0800, Matt Gilson wrote:
> For whatever weight my opinion holds, I'm +0 on this one.  In my
> estimation, in an ideal world it seems like:
>     class Foo(object):
>          def bar(self):
>              """Bar!"""
>     # Identical to:
>     class Foo(object): pass
>     def Foo.bar(self):
>         """Bar!"""
> But I think that's going to be hard to achieve given implicit binding of
> `super` (as some have already mentioned) and more mind-bendingly when
> user-defined metaclasses are in play.

I think that this is too high a bar to reach (pun not intended). A 
metaclass can do anything it likes to the methods in the class, and 
injecting a method after the class already exists is not necessarily the 
same as including it in the initial namespace argument passed to the 

I think a more reasonable bar is to have

def Foo.bar(self): ...

equivalent to

def bar(self): ...
Foo.bar = bar  # Foo is a class
del bar

except that the usual class magic like setting __qualname__, super() 
etc will work. That feels doable.

For instances, the invariant should be slightly different:

def bar(self): ...
foo.bar = types.MethodType(bar, foo)  # foo is an instance
del bar

> Indeed, with metaclasses, it seems
> like it become impossible to actually guarantee the equality of the above
> two blocks of code.  Maybe the PEP writers are OK with that, but that
> should be decided at the outset...


> Also note that if users start adopting this as their default mode of class
> creation (rather than just *class extending*), code-folding in a lot of
> IDEs won't handle it gracefully (at least not for quite a while).

Why would people use this as the default mode of class creation?

I mean, sure there's always that *one guy* who insists on their own 
weird idiosyncratic way of doing things. I know somebody who refuses to 
use for loops, and writes all his loops using while. But I can't see 
this becoming a widespread practice. We all have our quirks, but most of 
our quirks are not that quirky.


More information about the Python-ideas mailing list