Hacker News new | ask | show | jobs
by cgranade 5385 days ago
The only thing that I might ever want from functional and symbolic programming paradigms that I can't imagine how to emulate with decorators would be the ability to transform the actual compiled function object in some way. Python decorators can add lots of new code, sure, but they don't get access to the syntax tree for the function object to be able to break it apart and transform it.

Mind you, I truly love Python decorators, but I just don't think the comparison to languages like LISP quite holds up. Maybe I'm just inexperienced, though...

1 comments

I'm going to hell for this, but here goes. A couple years back I wrote a library called Transformana ( https://github.com/daeken/Transformana ) which allows you to manipulate ASTs via 'macros' in decorators. I apologize from the bottom of my heart to anyone who ends up maintaining code that utilizes this, but have fun.

https://github.com/daeken/Transformana/blob/master/test.py shows off various features if you're interested.

Edit: Here's the output from running the test, in case you want to see the AST format.

    Hello world!
    Yep, working.
    Don't know.
    ['function',
     None,
     'test2',
     (),
     (),
     0,
     None,
     ['stmt', [['printnl', [['const', 'Hello from test2']], None]]]]
    Hello from test2
    ['function', None, 'test3', (), (), 0, None, ['stmt', [['printnl', [['const', 'This should never be callable']], None]]]]
Fellow hell-bound soul here. I didn't go nearly as far as you did. I decided it would be fun to have guards in Python and decorators were just the tool. I sketched this out as part of a talk at Open Source Bridge a few years back:

https://github.com/built/Jane-Kelly/blob/master/guard.py

It'll let you redefine functions with different guard parameters. (@when("x=5"), @when("x>20"), etc.) Like you, I would also shudder to see this in production. But it was fun and shows off some of what's possible.