Last active
December 6, 2016 09:47
-
-
Save odedlaz/d1d295a1062b9d1f49bddc5c040bc853 to your computer and use it in GitHub Desktop.
compiled_exec_print.py
This file contains hidden or 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
from __future__ import print_function | |
import os | |
import sys | |
import six | |
from time import time | |
from random import choice | |
from string import Formatter | |
from string import ascii_letters | |
from inspect import currentframe | |
string_formatter = Formatter() | |
six.moves.builtins.std_print = print | |
def random_string(length=20): | |
""" | |
generate a random string of given length | |
""" | |
return "".join(choice(ascii_letters) | |
for _ in range(length)) | |
class TextObject(object): | |
__slots__ = ["code", "text"] | |
def __init__(self, text, code): | |
self.text = text | |
self.code = code | |
@classmethod | |
def from_text(cls, text): | |
keywords = {random_string(): kw for _, kw, _, _ | |
in string_formatter.parse(text) if kw} | |
code = ["__keywords={}"] | |
line_code = "__keywords[\"{kw_name}\"] = {kw_statement}" | |
for key, value in six.iteritems(keywords): | |
code.append(line_code.format(kw_name=key, | |
kw_statement=value)) | |
text = text.replace("{{{}}}".format(value), | |
"{{{}}}".format(key)) | |
return cls(text=text, | |
code="\n".join(code)) | |
@classmethod | |
def compile(cls, text): | |
obj = cls.from_text(text) | |
compiled = compile(obj.code, '<string>', 'exec') | |
return cls(code=compiled, text=obj.text) | |
memoize = {} | |
def print(text, **kwargs): | |
caller = currentframe().f_back | |
text_obj = memoize.get(text) | |
if not text_obj: | |
memoize[text] = text_obj = TextObject.compile(text) | |
exec(text_obj.code, caller.f_globals, caller.f_locals) | |
std_print(text_obj.text.format(**caller.f_locals["__keywords"]), **kwargs) | |
devnull = open(os.devnull, 'w') | |
name = "oded" | |
t = time() | |
for _ in range(50000): | |
print("my name is {name} & 2*3={2*3}", file=devnull) | |
std_print("block took {0:.3f} seconds".format(time() - t)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment