def read_str(abstr_tree): dotree = hy.read_str(f"(do {abstr_tree})") outtree = dotree[1:] if len(outtree) == 1: return outtree[0] else: return hy.HyExpression(list(outtree))
def on_command(self, command, args, chan, *_args, **_kwargs): if command == "!hy": if hy is None: self.reply(chan, "Hy is not installed") return try: tree = hy_compile(hy.read_str(args), "__main__") except Exception as ex: # I don't like catching all but I don't know how many errors this can throw self.reply(chan, "Parsing Error: " + str(ex)) return else: try: tree = ast.parse(args) except SyntaxError as ex: self.reply(chan, "Syntax Error: " + str(ex)) return returnval = None error = None self.aeval.writer = io.StringIO() try: returnval = self.aeval.eval_ast(tree) except asteval.UserError as e: error = e.error except asteval.EvalError as e: error = e except RecursionError as e: error = e if returnval is not None: self.reply(chan, str(returnval)) stdout = self.aeval.writer.getvalue() if stdout: self.reply(chan, stdout) if error is not None: self.reply(chan, str(error.__class__.__name__) + ": " + str(error))
def test_compound_model_repr(): HY_LIST_MODELS = (HyExpression, HyDict, HySet, HyList) with pretty(False): for model in HY_LIST_MODELS: assert eval(repr(model())).__class__ is model assert eval(repr(model([1, 2]))) == model([1, 2]) assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3]) for k, v in PRETTY_STRINGS.items(): # `str` should be pretty, even under `pretty(False)`. assert clean(str(hy.read_str(k))) == v for k in PRETTY_STRINGS.keys(): assert eval(repr(hy.read_str(k))) == hy.read_str(k) with pretty(True): for model in HY_LIST_MODELS: assert eval(clean(repr(model()))).__class__ is model assert eval(clean(repr(model([1, 2])))) == model([1, 2]) assert eval(clean(repr(model([1, 2, 3])))) == model([1, 2, 3]) for k, v in PRETTY_STRINGS.items(): assert clean(repr(hy.read_str(k))) == v
def test_compound_model_repr(): HY_LIST_MODELS = (HyExpression, HyDict, HySet, HyList) with pretty(False): for model in HY_LIST_MODELS: assert eval(repr(model())).__class__ is model assert eval(repr(model([1, 2]))) == model([1, 2]) assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3]) for k, v in PRETTY_STRINGS.items(): # `str` should be pretty, even under `pretty(False)`. assert str(hy.read_str(k)) == v for k in PRETTY_STRINGS.keys(): assert eval(repr(hy.read_str(k))) == hy.read_str(k) with pretty(True): for model in HY_LIST_MODELS: assert eval(repr(model())).__class__ is model assert eval(repr(model([1, 2]))) == model([1, 2]) assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3]) for k, v in PRETTY_STRINGS.items(): assert repr(hy.read_str(k)) == v
def nsHyEval(ns, expression): env = nsHYmkenv(ns) env = nsImportPfun(ns, env, "/psbin", "/pbin") try: _expr = read_str(str(expression)) _res = eval(_expr, env) except Exception as e: nsGlobalError(ns, "{}".format(e)) return None return _res
def __ein_eval_hy_string(obj): try: import hy except ImportError: print("Hy not supported in this kernel. Execute `pip install hy` if you want this support.") expr = hy.read_str(obj) ret = hy.eval(expr) return ret
def eval_hy_string(obj): try: import hy except ImportError: print("Hy not supported in this kernel. Execute `pip install hy` if you want this support.") expr = hy.read_str(obj) ret = hy.eval(expr) return ret
def nsHyEvalRestrict(ns, expression, *path): env = {} env = nsImportPfun(ns, env, *path) print(list(env.keys())) try: _expr = read_str(str(expression)) _res = eval(_expr, env) except Exception as e: nsGlobalError(ns, "{}".format(e)) return None return _res
def hy(self, code): if hy is None: self.log(hyErr) return expr = hy.read_str(code) self.log(hy.eval(expr, self.evalArgs))
def read_forms(abstr_tree): dotree = hy.read_str(f"(do {abstr_tree})") outtree = dotree[1:] return list(outtree)
def eval_str(s): return hy.eval(hy.read_str(s))
# tUtils.py - Utils written by TDL9 # Import this module as t # import numpy as np import functools as fn import itertools as itt import hy # eval Hy expression # see hy document for more details hyc = hy.eval(hy.read_str("(comp hy.eval hy.read_str)")) # functools.reduce(function, iterable[, initializer]) reduce = fn.reduce # built-in function, filter(function, iterable) ~= (item for item in iterable if function(item)) filter = filter # built-in function, map(function, iterable, ...) map = map # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 starmap = itt.starmap # product(p, q, … [repeat=1]) product = itt.product # flatten ["foo" (, 1 2) [1 [2 3] 4] "bar"] => ['foo', 1, 2, 1, 2, 3, 4, 'bar'] flatten = hyc("flatten") # return reversed iterator
def eval_str(s): return hy_eval(hy.read_str(s), filename='<string>', source=s)
import hy cool = hy.read_str("(+ 1 2)") print hy.eval(cool)
def test_hy_python_require(): # https://github.com/hylang/hy/issues/1911 test = "(do (require [tests.resources.macros [test-macro]]) (test-macro) blah)" assert hy.eval(hy.read_str(test)) == 1
def eval(self, code): self._code = code code = f"(do (require [hy.extra.anaphoric [*]]) {code})" expr = hy.read_str(code) self._value = hy.eval(expr)
def hy_eval_in_ns(code, ns): """Return the result of evaluating the given Hy code in the given namespace.""" return hy.eval(hy.read_str("(do\n" + code + "\n)\n"), locals=ns, module=sys.modules[ns['__name__']])
async def event_handler(self, details, websocket): if details == None: return None if details[1] == 0: return False # was just unpressed # Check if if details[0] in ['start', 'select']: # our control actions. if details[0] == "start": print("> Executing") try: expression = hy.read_str(self.typer.display_line( self.line)) print("Result:", hy.eval(expression)) self.last_returned = hy.eval(expression) except Exception as e: print("Exception:", e.__str__()) elif details[0] == "select": self.typer.remove_line(self.line) else: # Are we in prediction mode or not if self.mode == "PREDICT": result = self.typer.predict_handler(details[0], self.line) if (result != None): if result == "next_prediction": self.curr_pred = (self.curr_pred + 1) \ % len(self.predictions_found) elif result == "prev_prediction": self.curr_pred = (self.curr_pred - 1) \ % len(self.predictions_found) elif result == "select_prediction": self.typer.append_to_pos( self.line, (self.predictions_found[self.curr_pred] + " ")[len(self.curr):]) self.mode = "INSERT" self.predictions_found = [] self.curr_pred = [] elif result == "exit_prediction_mode": self.mode = "INSERT" self.predictions_found = [] self.curr_pred = [] elif self.mode == "INSERT": result = self.typer.add_key(details[0], self.line) # check if the user typed a special key combo if (result != None): if result == 'up_line': self.line -= 1 if self.line <= 0: self.line = 0 elif result == 'down_line': if self.line < self.typer.lines() - 1: self.line += 1 elif self.line == self.typer.lines() - 1: self.line += 1 self.typer.new_line() elif result == 'pos_left': self.typer.changepos(self.line, self.typer.pos(self.line) - 1) elif result == 'pos_right': self.typer.changepos(self.line, self.typer.pos(self.line) + 1) elif result == 'remove_current': self.typer.remove_key(self.line) elif result == 'predictive_mode': self.mode = "PREDICT" self.predictions() # Get word we are working on # Stupid prompt. prompt = "dp {} {} {} {}> ".format(self.mode,self.line, \ self.typer.pos(self.line), \ self.typer.inprogress(self.line)) print("{} {}".format(prompt, self.typer.display_line(self.line))) print("{} ^".format(" " * (len(prompt) + self.typer.pos(self.line)))) if self.mode == "PREDICT": print("Prediction:") i = 0 for pred in self.predictions_found: print("{} {}".format([" ", "*"][i == self.curr_pred], pred)) i += 1 everything = { "mode": self.mode, "line": self.line, "pos": self.typer.pos(self.line), "progress": self.typer.inprogress(self.line), "line_text": self.typer.display_line(self.line), "predictions": self.predictions_found, "current_prediction": self.curr_pred, "last_output": "" } await websocket.send(json.dumps(everything))
cyear, centity) else: guts = 'This work is licensed under {}. Copyright {} {}.'.format( license_html[license_url], year_created if year_created and not info['daylight-show-mdate'] else '{}–{}'.format(year_created, year_modified) if year_created and year_created != year_modified else year_modified, authors_html) text = text.replace(rep, '<footer id="license-footer"><p>{}</p></footer>'.format(guts) + rep) # Apply any post-processing block defined by the file. if info['postproc']: lang, _, body = info['postproc'].partition('\n') if lang == 'python': exec(body) text = POSTPROC(text) elif lang == 'hy': import hy POSTPROC = hy.eval(hy.read_str("(fn [text]\n" + body + "\n)")) text = POSTPROC(text) else: raise ValueError("Unknown POSTPROC language " + repr(lang)) # Done. print(text, end = '')
def process(value): return hy.read_str(from_json(value))
def nsHyEval(ns, expression): env = nsHYmkenv(ns) env = nsImportPfun(ns, env, "/psbin", "/pbin") _expr = read_str(str(expression)) _res = eval(_expr, env) return _res