Skip to content

Instantly share code, notes, and snippets.

@odedlaz
Last active December 6, 2016 09:47
Show Gist options
  • Save odedlaz/edbe95c61c19740855f1b4dd7b2a99d3 to your computer and use it in GitHub Desktop.
Save odedlaz/edbe95c61c19740855f1b4dd7b2a99d3 to your computer and use it in GitHub Desktop.
exec_print.py
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))
memoize = {}
def print(text, **kwargs):
caller = currentframe().f_back
text_obj = memoize.get(text)
if not text_obj:
memoize[text] = text_obj = TextObject.from_text(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