Created
July 19, 2026 20:20
-
-
Save reece/4818230be643b77247d94d6b3e1cd84e to your computer and use it in GitHub Desktop.
Parser subclass example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # » python3 ./archive/parser-subclass-example.py | |
| # Parser() -> Type: ParsleyParser | |
| # grammar = __parsley__ | |
| # ---------------------------------------- | |
| # Parser(grammar_fn=Parser.PARSELY_PARSER) -> Type: ParsleyParser | |
| # grammar = __parsley__ | |
| # ---------------------------------------- | |
| # Parser(grammar_fn=Parser.PYPARSING_PARSER) -> Type: PyParsingParser | |
| # grammar = __pyparsing__ | |
| class Parser: | |
| PARSELY_PARSER = "__parsley__" | |
| PYPARSING_PARSER = "__pyparsing__" | |
| def __new__(cls, grammar_fn=PARSELY_PARSER, *args, **kwargs): | |
| if cls is Parser: | |
| if grammar_fn == Parser.PARSELY_PARSER: | |
| return super().__new__(ParsleyParser) | |
| elif grammar_fn == Parser.PYPARSING_PARSER: | |
| return super().__new__(PyParsingParser) | |
| else: | |
| raise ValueError(f"Unknown parser type: {grammar_fn}") | |
| return super().__new__(cls) | |
| def __init__(self, grammar_fn=PARSELY_PARSER, *args, **kwargs): | |
| self.grammar_fn = grammar_fn | |
| def which_grammar(self): | |
| return f"grammar = {self.grammar_fn}" | |
| class ParsleyParser(Parser): | |
| pass | |
| class PyParsingParser(Parser): | |
| pass | |
| p_default = Parser() | |
| print(f"Parser() -> Type: {type(p_default).__name__}") | |
| print(p_default.which_grammar()) | |
| print("-" * 40) | |
| p_parsley = Parser(grammar_fn=Parser.PARSELY_PARSER) | |
| print(f"Parser(grammar_fn=Parser.PARSELY_PARSER) -> Type: {type(p_parsley).__name__}") | |
| print(p_parsley.which_grammar()) | |
| print("-" * 40) | |
| p_pyparsing = Parser(grammar_fn=Parser.PYPARSING_PARSER) | |
| print(f"Parser(grammar_fn=Parser.PYPARSING_PARSER) -> Type: {type(p_pyparsing).__name__}") | |
| print(p_pyparsing.which_grammar()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment