On Sat, 19 Dec 2020 03:52:46 +0100 Marco Sulla Marco.Sulla.Python@gmail.com wrote:
Maybe it's a crazy idea, but what if we could decorate a single line of code?
That's definitely useful, as a generic programming language concept. My favorite example is from (embedded) C, where I'd like to have per-callsite control of whether a function is inlines, or vice-versa, not inlined:
(Using imaginary syntax which overloads C comments)
// Annotation is actually per-expression foo() + /*#inline*/bar()
But I yet to see a compelling usecase for Python.
@Timer a = time_consuming_function()
Syntax-wise, I don't see any problems. As I mentioned in a recent mail, "@" here is effectively a prefix operator (unary in first approximation).
But is that really compelling usecase? What if you want to time 2 statements?
This will be equivalent to using Steven's context manager, but the decorator is more simple to comment and uncomment.
Maybe it could be possible to comment also code blocks:
Definitely, if such a feature would be introduced, it would apply to any statement, whether simple or compound.
@parallel for x in y: do_something(x) now_something_completely_different(x)
This could be a shortcut for multiprocessing.
... Defining a semantics would be harder. Where @ operator applies now, it takes a "named suite" (class or function) and
@deco NAMED_SUITE name
is (roughly) equivalent to:
NAMED_SUITE tmp name = deco(tmp) del tmp
No specific semantics could be assigned to per-statement decorators, so the best idea is probably to treat such per-statement decorators as purely syntactic feature, a kind of macro. On AST level, it would produce something like ast.Decorated, to which statement(s) attached as children, so you would need to write an AST transformer, or just subclass bytecode compiler, to implement it.
Bottom line: this should be doable, and should be doable easily enough by any interested party.