Dec-23-2017, 09:57 PM
(This post was last modified: Dec-25-2017, 12:04 AM by RickyWilson.)
Here is a very basic object orientated implementation of a read evaluate print loop AKA REPL. I encluded REShell to demonstrate how one could use Reple.
I would like to know the quality of this code.
I would like to know the quality of this code.
- Is it easy to read and understand
- Is there any bugs I missed.
- Would this be better implemented using functions instead of the class driven object orientated approach.
#-*-coding:utf8;-*- #qpy:3 #qpy:console import re import sre_constants PS1 = '>> ' class Repl(object): def __init__(self, ps1=PS1): self.ps1 = ps1 def read(self): return input(self.ps1) def evaluate(self): raise NotImplementedError('You must define this in a sub-class') def run(self): while 1: try: self.evaluate() except KeyboardInterrupt: sys.exit(1) class REShell(Repl): def __init__(self, data, ps1=PS1): self.ps1 = ps1 self.data = data def evaluate(self): try: user_input = self.read() expression = re.compile(user_input) print(*expression.findall(self.data), sep='\n') print(user_input) except sre_constants.error as error: print(error) def source_code(): with open(__file__, 'r') as source: return source.read() if __name__ == '__main__': data = source_code() print(data) shell = REShell(data) shell.run()