3 ms·
Neat. I'd sometimes wondered if munging the AST in a decorator to add some new control flow was practical. The code looks a bit fragile but not excessively pain
by tlb 15y ago
Neat. I'd sometimes wondered if munging the AST in a decorator to add some new control flow was practical. The code looks a bit fragile but not excessively painful.
- albertzeyer 15y agoThe problem is that in the decorator, you just get the compiled function. So you can modify the bytecode but not operate on the AST anymore. I thought about this and wrote a patch for CPython that it also stores the original AST of any compiled function in the function object. Some discussion about this: http://thread.gmane.org/gmane.comp.python.devel/126754 http://thread.gmane.org/gmane.comp.python.devel/126754 http://thread.gmane.org/gmane.comp.python.devel/126760 http://thread.gmane.org/gmane.comp.python.devel/126760
- sitkack 15y agoYou can find the line number that the func was defined in and reparse the source. I do this in quite a few decorators that need source. The other option is to wrap the thing decorated in a doc string @fancy_source_needing_decorator def foo(s): """ put some haskell or DSL stuff in here """ Then you don't have to reparse the source, etc etc, but it still gets packaged as a function.
- drx 15y agoWould you mind linking to some examples? I'd love to read them.
- cheatercheater 15y agoI remember this being used in a unit testing framework of some sort.. maybe twisted's?