What about using a simple decorator instead? def monkey_patch(cls): return lambda func: setattr(cls, func.__name__, func)
class Foo: pass @monkey_patch(Foo) def bar(self): return 42 Foo().bar() # gives 42 2017-02-10 11:15 GMT+01:00 Matthias welp <boekew...@gmail.com>: > Hi Markus, > > Thanks for writing this up, as I've had this same very valid problem > before. > > On 10 February 2017 at 10:13, Markus Meskanen <markusmeska...@gmail.com> > 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. > > Your solution to me seems like a 'hack': class monkey-patching during > runtime > is already available if you really need it, and your proposal only > makes it easier, > which I don't really like. > > > 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 > > This problem could just as well be solved by allowing access to a > scope-level > variable (__class__? __type__?) which is available in the class body at > construction time, which points to the (eventual) class type object, > or evaluating > the type hints in a class only after the class is created, which then > allows for that > class to be pointed to in the type annotations. > > E.G. this does not work right now: > > class A: > def foo(self: A): > pass > > as it fails with NameError: A is not defined, whereas you'd expect it to > work. > > The problem is very annoying when you're trying to work with the dunder > methods for e.g. numerical objects, as you cannot say '+ is only allowed > for > these types', but it is not limited to this scope only. > > > -Matthias > _______________________________________________ > Python-ideas mailing list > Python-ideas@python.org > https://mail.python.org/mailman/listinfo/python-ideas > Code of Conduct: http://python.org/psf/codeofconduct/ >
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/