[Python-ideas] Fwd: Define a method or function attributeoutsideof a class with the dot operator
steve at pearwood.info
Mon Feb 13 20:06:57 EST 2017
On Sun, Feb 12, 2017 at 10:29:10PM +0100, Nick Coghlan wrote:
> Method injection is most attractive to me as a potential alternative
> to mixin classes that has fewer runtime side effects by moving more of
> the work to class definition time.
> More philosophically though, it offends my language design
> sensibilities that we have so much magic bound up in class definitions
> that we don't expose for procedural access post-definition time -
> there's a whole lot of behaviours that "just happen" when a method is
> defined lexically inside a class body that can't readily be emulated
> for callables that are defined outside it.
If the OP is willing to write a PEP, I think it is worth taking a
- expose the class definition magic that Nick refers to;
- which will allow writing a proper inject_method() decorator;
- or allow def Class.method syntax.
I think I would prefer
def Class.method ...
def method ...
but given how high the barrier to new syntax is, perhaps we should be
willing to take the decorator approach and leave the syntax for the
future, once people have got used to the idea that extension methods
won't cause the fall of civilization as we know it :-)
> However, even with that, I'm still only +0 on the idea - if folks
> really want it, `types.new_class` can already be used to creatively to
> address most of these things, and it's not exactly a problem that
> comes up very often in practice.
Swift and Objective-C users might, I think, disagree with that: they
even have a term for this, "swizzling". This is part of the
"Interceptor" design pattern:
More information about the Python-ideas