Unexpected Syntaxerror With Decorators
Here the goal is to call a global function as a decorator. #coding: utf-8 def Test(method_to_decorate): print 'Decorator' def wrapper(self): return method_to_decor
Solution 1:
It's a SyntaxError because Python's grammar explicitly does not allow that; the tokens on the right of @
are not an expression. 1 Instead, valid syntax is:
decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
(A phrase enclosed in square brackets ([ ]
) means zero or one occurrences (in other words, the enclosed phrase is optional).) 2
Following from the above, you can get this to work by converting globals()['Test']
to a dotted name. The following examples should work:
g = globals()
@g.get('Test')defFun(self):
pass
x = globals()['Test']
@xdefFun(self):
pass
Or, as you noticed, you can just skip the syntactic sugar and decorate manually, which is probably the least bad option.
Solution 2:
Because the Python parser isn't designed to recognize an index access as part of decorator syntax. Consider writing a separate function that accesses globals()
instead.
Post a Comment for "Unexpected Syntaxerror With Decorators"