Possibility for method decorators?
I was thinking a bit about method decorators, and I just wanted to ask your opinion on the viability of this method.
What if, for decorated methods, instead of generating a function like this:
get funcName() {
return __get__ (this, function (self) {
// actual function innards
});
},
we did this:
function __impl__funcName(self) {
// actual function innards
},
get funcName() {
return __get__(this, this.__impl_funcName);
},
If I'm thinking correctly, this would allow us to then send __inner_funcName through any decorators after we declare the class. I don't know how well it would play with class decorators, but it would at least allow us to run the method through a python-like decorator and have the changes persist after class creation.
I haven't dug too much into Transcrypt's code generation yet, but if you think that this would be possible to do, I would definitely be willing to work on this feature.
Without solidly overseeing all the consequences:
This seems like a viable inroad to support method decorators.
And if I understand right, it would not bring any overhead for undecorated methods, just extra JS code as you propose for decorated methods.
That would be very nice. And in the Transcrypt / Python source code such method decorators would just follow standard Python syntax, wouldn't they? Very clever, as far as I can see. Consequences would be quite local in both the compiler,py and core.mod.js.
If you're willing to, please give it a try!
PS. Beware of the (limited) complexities of call caching, but I don't think they are a show stopper. There may be some interactions with other features, but I expect these to be solvable. The shipment test will tell us quick enough.
PS2. Be sure to use a version of Transcrypt >= 2.5.233, since some things have changed in compiler,py and core.mod.js, due to the introduction of metaclasses. This shouldn't have much (or even any) consequences for the viability of your idea.
PS3. My plan is to start working on async / await, but that will be in a completely different part of compiler.py, so a merge should not pose a problem.
PS4. When your not logged into GitHub, your name is currently not visible in the list of organisation members. This is a bit of a shame, since you are an active contributor. Could be you deliberately choose to keep a low profile, which is of course OK. But if it wasn't a deliberate choice, consider making your involvement visible to non-member developers, as explained at: https://help.github.com/articles/publicizing-or-hiding-organization-membership/
Hi
Still working on this or should I postpone + close or withdraw + close this?
KR J
I have a bit, but I haven't done too much work on getting it actually working recently.
Feel free to postpone+close, I can comment to reopen if/when I get something actually complete!
Ok!
KR J
Based on your idea I made a compiler patch. I have no time to carefully test it, but for simple cases it works. Tested with this code:
def method_decorator(method):
def wrapper(instance, a, b):
console.log('from method wrapper')
return method(instance, a * 2, b * 2)
return wrapper
def class_decorator(arg):
def wrapper(cls):
# console.log(cls)
# console.log(arg)
console.log('from class wrapper')
return cls
return wrapper
@class_decorator('abc')
class MyClass:
def __init__(self):
self.variable = '123'
@method_decorator
def mymethod(self, a, b):
return a + b
@classmethod
def myclassmethod(cls):
console.log(cls.variable) # must be undefined
console.log(cls.__name__)
@staticmethod
def mystaticmethod(a, b):
console.log(a, b)
myobj = MyClass()
result = myobj.mymethod(2, 3)
console.log(result)
myobj.myclassmethod()
MyClass.myclassmethod()
myobj.mystaticmethod(4, 5)
MyClass.mystaticmethod(4, 5)
Everything works, except static method when called from an instance, because it is passing self as first parameter. Until next week, I have no time to look at this case. But you can use my patch as a starting point. Btw, I fixed classmethod to use class, not instance just by reassigning first parameter to class itself. I know this is ugly, but at least it's temporary solution to call class methods as in python.
P.S. seems that this classmethod fix will not work with with inherited classes, so we need another solution for such cases.
Shouldn't you make this a pull request?
@pmukherjeee maybe, next week, I just created it quickly last night and don't have enough time to test it.
After modifying javascript by hand, I think I found the solution for classmethod problem. If method has classmethod decorator, then we can define different __get__ function and rename it like __getcm__, then in core we can add __getcm__ like this:
var __getcm__ = function (self, func, quotedFuncName) {
if (self.hasOwnProperty ('__class__')) {
return function () {
var args = [] .slice.apply (arguments);
return func.apply (null, [self.__class__] .concat (args));
};
}
else {
return function () {
var args = [] .slice.apply (arguments);
return func.apply (null, [self] .concat (args));
};
}
}
__all__.__getcm__ = __getcm__;
In this case, no matter if the caller is a class or instance, we always get class as first parameter. So transcrypt when compiling must check if the method has classmethod decorator and emit __getcm__ instead of __get__ for example:
get myclassmethod () {return __getcm__ (this, function (cls) {
console.log(cls.__name__);
});}
What do you think about that?
I made a fork and tested with this test:
def method_decorator(method):
def wrapper(instance, a, b):
autoTester.check(a, b)
return method(instance, a * 2, b * 2)
return wrapper
def method_decorator2(method):
def wrapper(instance, a, b):
autoTester.check(a, b)
return method(instance, a * 3, b * 3)
return wrapper
def classmethod_decorator(method):
def wrapper(cls, a, b):
autoTester.check(cls.__name__, a, b)
return method(cls, a * 2, b * 2)
return wrapper
def class_decorator(arg):
def wrapper(cls):
autoTester.check(cls.__name__)
return cls
return wrapper
@class_decorator('outer')
class MyClass:
@class_decorator('inner')
class InnerClass:
@method_decorator
@method_decorator2
def mymethod(self, a, b):
autoTester.check(a + b)
@classmethod
@classmethod_decorator
def myclassmethod(cls, a, b):
autoTester.check(a + b)
@staticmethod
def mystaticmethod(a, b):
autoTester.check(a + b)
@method_decorator
@method_decorator2
def mymethod(self, a, b):
autoTester.check(a + b)
@classmethod
def myclassmethod(cls):
autoTester.check(cls.__name__)
@staticmethod
def mystaticmethod(a, b):
autoTester.check(a + b)
def run(self):
inner_obj = self.InnerClass()
inner_obj.mymethod(2, 3)
inner_obj.myclassmethod(6, 7)
self.InnerClass.myclassmethod(6, 7)
inner_obj.mystaticmethod(4, 5)
self.InnerClass.mystaticmethod(4, 5)
myobj = MyClass()
myobj.mymethod(2, 3)
myobj.myclassmethod()
MyClass.myclassmethod()
myobj.mystaticmethod(4, 5)
MyClass.mystaticmethod(4, 5)
myobj.run()
classmethod, staticmethod work like in python (even with additional decorators), method decorators are working too (single, multiple and for inner classes). Transcrypt autotests passed without errors.
Hi,
Seems you have solved this long standing problem at minimum expense! I still want to take a real good look, have to find the time for that. Won't be long.
Kind regards Jacques
I have taken a first look and I find I need a little help in understanding. In some cases you use the __impl__ prefix. I guess __impl__ means implementation and you're avoiding a name clash here, probably between decorated and "bare" version of the function. You seem to be using it even in the case of "normal" function decorators, where previously no prefix was needed.
Can you enlighten me on which names exactly are clashing. And it seems they weren't clashing when there were only "normal" (as opposed to class and method) decorators. Could you pinpoint for me why in the new situation they are. So how is it that even decorators for "normal" functions now need this prefixed name somehow.
Probably I should be able to answer this question by studying your code more carefully. But a little help would be welcome. (Maybe in the form of some added comments, since for me this isn't obvious, but I may be missing something very trivial here...)
__impl__ is prefixed only for class methods, bare methods are passed to emitDecorators() with "callable" prameter, so they work exactly as before. Method decorators are pushed to self.classDecorators (nodes and scopes) and after the outer class is created, then all those decorators are asigned from that list. emitDecorators() in such case is called without "callable" parameter.
Btw, I run standard decorator autotest from transcrypt and javascript for old decorators looks the same as before. And my new part looks like this:
var MyClass = __class__ ('MyClass', [object], {
InnerClass: __class__ ('InnerClass', [object], {
get __init__ () {return __get__ (this, function (self) {
self.variable = '123';
});},
__impl__mymethod: function (self, a, b) {
autoTester.check (a + b);
},
get mymethod () {return __get__ (this, this.__impl__mymethod);},
__impl__myclassmethod: function (cls, a, b) {
autoTester.check (a + b);
},
get myclassmethod () {return __getcm__ (this, this.__impl__myclassmethod);},
get mystaticmethod () {return function (a, b) {
autoTester.check (a + b);
}}
}),
get __init__ () {return __get__ (this, function (self) {
self.variable = '123';
});},
__impl__mymethod: function (self, a, b) {
autoTester.check (a + b);
},
get mymethod () {return __get__ (this, this.__impl__mymethod);},
get myclassmethod () {return __getcm__ (this, function (cls) {
autoTester.check (cls.__name__);
});},
get mystaticmethod () {return function (a, b) {
autoTester.check (a + b);
}},
get run () {return __get__ (this, function (self) {
var inner_obj = self.InnerClass ();
inner_obj.mymethod (2, 3);
inner_obj.myclassmethod (6, 7);
self.InnerClass.myclassmethod (6, 7);
inner_obj.mystaticmethod (4, 5);
self.InnerClass.mystaticmethod (4, 5);
});}
})
MyClass.InnerClass.__impl__mymethod = method_decorator2 (MyClass.InnerClass.__impl__mymethod)
MyClass.InnerClass.__impl__mymethod = method_decorator (MyClass.InnerClass.__impl__mymethod)
MyClass.InnerClass.__impl__myclassmethod = classmethod_decorator (MyClass.InnerClass.__impl__myclassmethod)
MyClass.InnerClass = class_decorator ('inner') (MyClass.InnerClass)
MyClass.__impl__mymethod = method_decorator2 (MyClass.__impl__mymethod)
MyClass.__impl__mymethod = method_decorator (MyClass.__impl__mymethod)
var MyClass = class_decorator ('outer') (MyClass);
var myobj = MyClass ();
myobj.mymethod (2, 3);
myobj.myclassmethod ();
MyClass.myclassmethod ();
myobj.mystaticmethod (4, 5);
MyClass.mystaticmethod (4, 5);
myobj.run ();
And classmethod, staticmethod are decorated only when there are more decorators on the same method e.g.:
@classmethod
@decorator_for_classmethod
def somefunction(cls):
...
Otherwise they are just called with __getcm__, __getsm__ functions (to correctly pass cls or nothing), but remains the same as before.
P.S. actually staticmethod (if alone) is returning it's function immediately, because it doesn't need cls or self:
get mystaticmethod () {return function (a, b) {
autoTester.check (a + b);
}},
@JdeH Is it clearer now? You see this code can't be run without some prefix:
mymethod: function (self, a, b) {
autoTester.check (a + b);
},
get mymethod () {return __get__ (this, this.mymethod);}
It will raise "ERROR - Object literal contains illegal duplicate key "mymethod", disallowed in strict mode"
Yes, it's clear to me now when and why you use the prefix. Your solution is a very good one in my view. I've run the shipment test on your code, including the -fastcall switch, and it all works fine.
My proposal would be that you add your test code to ../automated_tests/transcrypt as a testlet in a directory method_and_class_decorators and then issue a pull request. Note that you have to refer to it from autotest.py, just like the other testlets.
If that's a problem, I can do it as well. Will be pulling your code with pleasure! Really a great improvement.
Ok, I'll write tests for more use cases and will make a pull request. Just will ask to update documentation, because my english is bad. Later, I will add datetime module for which I actually made those changes. Some parts are working already, some needs corrections.
Since https://github.com/QQuick/Transcrypt/pull/385 was merged, I think this can be closed?
Thank you neriusmika for implementing this.
@daboross your idea was very good. Glad to help with implementation.