SoFunction
Updated on 2024-12-13

Python Design Patterns Behavioral Interpreter Patterns

I. Interpreter model

Interpreter mode, the developer to customize a "connotation" of the language (or called a string), and set the relevant rules of interpretation, the string can be input to the output of the recognized interpretation, or to perform the program can understand the action.

Pros:

  • Scalability is better and flexible.
  • Added new ways to interpret expressions.
  • Easy to implement simple grammar.

Drawbacks:

  • There are fewer available scenarios.
  • It's harder to maintain for complex grammars.
  • The interpreter model causes class bloat.

II. Application scenarios

  • SQL Parsing
  • symbol processing engine

III. Code examples

Entity Role:

  • Terminator expressions:Implements interpreted operations associated with elements in a grammar. Usually there is only one terminator expression in an interpreter pattern, but there are multiple instances corresponding to different terminators. Half of the terminators are units of operations in the grammar. For example, there is a simple formula R=R1+R2, in which R1 and R2 are terminators, and the corresponding interpreter that parses R1 and R2 is a terminator expression.
  • nonterminal expression: Each rule in the grammar corresponds to a non-terminal expression, which is usually an operator or other keyword in the grammar, e.g., in the formula R=R1+R2, "+" is a non-terminal, and the interpreter that parses "+" is The interpreter that parses "+" is a non-terminal expression. The number of non-terminal expressions increases according to the complexity of the logic, and in principle each grammar rule corresponds to a non-terminal expression.
import time
import datetime

"""Implementing a simple piece of Chinese programming."""


class Code:
    """Customized language"""
    def __init__(self, text=None):
         = text


class InterpreterBase:
    """Custom Interpreter Base Classes"""
    def run(self, code):
        pass


class Interpreter(InterpreterBase):
    """Implementing Interpreter Methods, Implementing Terminator Expression Dictionaries"""
    def run(self, code):
        code = 
        code_dict = {'Get current timestamp': (), "Get current date": ().strftime("%Y-%m-%d %H:%M:%S")}
        print(code_dict.get(code))


if __name__ == '__main__':
    test = Code()
     = 'Get current timestamp'
    data1 = Interpreter().run(test)
     = 'Get current date'
    data2 = Interpreter().run(test)

This article on Python Design Patterns Behavioral Interpreter Patterns is introduced to this article, more related Python Interpreter Patterns content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!