in englishthis function finds the first string in the text that matches the regular expressionoutputs everything from the current position to the start of that matchand then advances the position to the end of aforesaid match once it' out of matchesit outputs everything since the last position of courseignoring the directive is pretty useless in templating engineso let' set up replace that position advancing line with code that delegates to different method on the class depending on the directivedef process(self)match directive_re search(self templatepos=self poswhile matchself outfile write(self template[self pos:match start()]directiveargument match groups(method_name 'process_{}format(directivegetattr(selfmethod_name)(matchargumentmatch directive_re search(self templatepos=self posself outfile write(self template[self pos:]so we grab the directive and the single argument from the regular expression the directive becomes method name and we dynamically look up that method name on the self object ( little error processing here in case the template writer provides an invalid directive would be betterwe pass the match object and argument into that method and assume that method will deal with everything appropriatelyincluding moving the pos pointer now that we've got our object-oriented architecture this farit' actually pretty simple to implement the methods that are delegated to the include and variable directives are totally straightforwarddef process_include(selfmatchargument)with (self working_dir argumentopen(as includefileself outfile write(includefile read()self pos match end(def process_variable(selfmatchargument)self outfile write(self context get(argument'')self pos match end(the first simply looks up the included file and inserts the file contentswhile the second looks up the variable name in the context dictionary (which was loaded from json in the __init__ method)defaulting to an empty string if it doesn' exist