Created
February 11, 2020 19:32
-
-
Save remi6397/43a77fe9d925ad4bb7639de31fd089c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ # An example REPL session | |
$ python3 interpret.py | |
Python [REDACTED] (default, [REDACTED]) | |
[REDACTED] on [REDACTED] | |
Type "help", "copyright", "credits" or "license" for more information. | |
(InteractiveConsole) | |
>>> 10 | |
10 | |
>>> repr_map['int'] = bin | |
>>> 10 | |
0b1010 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import code | |
import codeop | |
repr_map = {} | |
def _wrap_repr(thing): | |
class AdHocWrapper(type(thing)): | |
def __repr__(self): | |
global repr_map | |
try: | |
return repr_map[thing.__class__.__name__](self) | |
except KeyError: | |
return super().__repr__() | |
return AdHocWrapper(thing) | |
REPL_EXPORT = { "_wrap_repr": _wrap_repr, "repr_map": repr_map } | |
class RewriteConstants(ast.NodeTransformer): | |
def visit_Constant(self, node): | |
return ast.Call( | |
func=ast.Name( | |
id="_wrap_repr", | |
ctx=ast.Load()), | |
args=[node], | |
keywords=[]) | |
visit_Num = visit_Constant | |
visit_Str = visit_Constant | |
visit_Bytes = visit_Constant | |
class TransformCompile(): | |
def __init__(self, transformers): | |
self.transformers = transformers | |
self.inferior = codeop.Compile() | |
def __call__(self, source, filename, symbol): | |
tree = compile(source, filename, symbol, ast.PyCF_ONLY_AST|0x200, True) | |
for trans in self.transformers: | |
ast.fix_missing_locations(trans.visit(tree)) | |
return self.inferior(tree, filename, symbol) | |
if __name__ == "__main__": | |
console = code.InteractiveConsole(REPL_EXPORT) | |
console.compile.compiler = TransformCompile([RewriteConstants()]) | |
console.interact() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment