4 ms·
I'm not a python programmer. But shouldn't this be possible at runtime by modifying the AST to change it back to import in the AST? That way you could have a mo
by lawl 13y ago
I'm not a python programmer. But shouldn't this be possible at runtime by modifying the AST to change it back to import in the AST? That way you could have a module you can just include to run this without a custom interpreter.
Edit: Looks like this is doable by messing with the tokenizer: http://stackoverflow.com/questions/214881/can-you-add-new-statements-to-pythons-syntax http://stackoverflow.com/questions/214881/can-you-add-new-st...
You could create a loader.py where you tokenize the script yourself, and replace accio with a custom import that again loadds imports by tokenizing them yourself first. And then after you've modified the tokens you should be able to build a valid AST and run it :)
I'm pretty sure you can just throw a SyntaxError there yourself too if you encounter a real "import".
Nice hack nevertheless.
- ThePhysicist 13y agoI think you wouldn't be able to generate a valid AST to begin with since the parser would probably complain that it doesn't know the "accio" keyword, but I'm note 100 % sure if there isn't a workaround for this.
- lvh 13y agoYes and no. The regular python parser will barf on that unknown keyword, so you don't get an ast because the parser never gets there. Using import hooks, this can be done in a regular interpreter. For example, that's how hy, a lisp in python, works!
- anon4 13y agoOh yes, you can. But once you're doing that, why stop at a single statement? Why not macros https://github.com/lihaoyi/macropy https://github.com/lihaoyi/macropy
- sitkack 13y agoDon't forget http://www.pocoo.org/projects/karnickel/#karnickel http://www.pocoo.org/projects/karnickel/#karnickel the magnificent