153 points · by ThePhysicist · 12y ago · 28 comments
At Hacker School, I've been building an alternate universe Python by overwriting builtin functions and statements with Harry Potter spells. This is a thing you can do at Hacker School!
import math
x = math.ceil(y)
into x = accio ceil(y)
and having it Just Magically Work (tm).But it's a nice write up of recompiling Python with a changed grammar.
Edit: Looks like this is doable by messing with the tokenizer: 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.
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!
Did you consider import hooks to accomplish this? Of course that wouldn't make your bootstrap language any different; that'd still be vanilla python. In the imported file you can do whatever you want, for example the inimitable paultag implemented hy, a python lisp, using those.
accio = __import__
Anyway, interesting article! In [1]: accio = __import__
In [2]: accio("os")
Out[2]: <module 'os' from '/usr/lib/python2.7/os.pyc'> >>> accio = __builtins__.__import__
>>> accio sys
File "<stdin>", line 1
accio sys
^
SyntaxError: invalid syntax
# :(
The author wanted accio to replace import not __import__.