diff --git a/yes.py b/yes.py new file mode 100644 index 0000000..c6d45ec --- /dev/null +++ b/yes.py @@ -0,0 +1,44 @@ +import inspect +from io import StringIO +import sys +import re + +did_you_mean = re.compile(r'Did you mean (.*)\?', re.IGNORECASE) +what = 'what?' + + +class Yes: + def __repr__(self): + try: + last_error = sys.last_value + except: + return what + + if not isinstance(last_error, Exception): + return what + + error_message = str(last_error) + + try: + suggestion = did_you_mean.search(error_message).group(1) + except Exception as e: + return what + + if not suggestion.startswith('print('): + suggestion_ = f'print({suggestion})' + else: + suggestion_ = suggestion + + frame = inspect.currentframe() + locals = frame.f_back.f_locals + del frame + + old_stdout = sys.stdout + eval_output = sys.stdout = StringIO() + + eval(suggestion_, globals(), locals) + sys.stdout = old_stdout + + return(f'>>> {suggestion} \n{eval_output.getvalue()[:-1]}') + +yes = Yes()