<div dir="ltr"><div>What about using a simple decorator instead?</div><div><br></div><div>def monkey_patch(cls):</div><div> return lambda func: setattr(cls, func.__name__, func)</div><div><br></div><div>class Foo:</div><div> pass</div><div><br></div><div><div>@monkey_patch(Foo)</div><div>def bar(self):</div><div> return 42</div></div><div><br></div><div>Foo().bar()</div><div># gives 42</div></div><div class="gmail_extra"><br><div class="gmail_quote">2017-02-10 11:15 GMT+01:00 Matthias welp <span dir="ltr"><<a href="mailto:boekewurm@gmail.com" target="_blank">boekewurm@gmail.com</a>></span>:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi Markus,<br>
<br>
Thanks for writing this up, as I've had this same very valid problem before.<br>
<span class=""><br>
On 10 February 2017 at 10:13, Markus Meskanen <<a href="mailto:markusmeskanen@gmail.com">markusmeskanen@gmail.com</a>> wrote:<br>
> I'm suggesting the addition of support to using a dot notation when defining<br>
> a function to be a method of a class, or a callback attribute.<br>
<br>
</span>Your solution to me seems like a 'hack': class monkey-patching during runtime<br>
is already available if you really need it, and your proposal only<br>
makes it easier,<br>
which I don't really like.<br>
<span class=""><br>
> This functionality would be useful in the few rare cases where the class<br>
> itself needs to be accessed in the function's definition (decorator, typing,<br>
> etc<br>
<br>
</span>This problem could just as well be solved by allowing access to a scope-level<br>
variable (__class__? __type__?) which is available in the class body at<br>
construction time, which points to the (eventual) class type object,<br>
or evaluating<br>
the type hints in a class only after the class is created, which then<br>
allows for that<br>
class to be pointed to in the type annotations.<br>
<br>
E.G. this does not work right now:<br>
<br>
class A:<br>
def foo(self: A):<br>
pass<br>
<br>
as it fails with NameError: A is not defined, whereas you'd expect it to work.<br>
<br>
The problem is very annoying when you're trying to work with the dunder<br>
methods for e.g. numerical objects, as you cannot say '+ is only allowed for<br>
these types', but it is not limited to this scope only.<br>
<span class="HOEnZb"><font color="#888888"><br>
<br>
-Matthias<br>
</font></span><div class="HOEnZb"><div class="h5">______________________________<wbr>_________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" rel="noreferrer" target="_blank">https://mail.python.org/<wbr>mailman/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" rel="noreferrer" target="_blank">http://python.org/psf/<wbr>codeofconduct/</a><br>
</div></div></blockquote></div><br></div>