ANTLR 4 Python 3 Runtime
raw JSON → 4.13.2 verified Tue May 12 auth: no python install: verified quickstart: stale
ANTLR (ANother Tool for Language Recognition) is a powerful parser generator. This library provides the Python 3 runtime for lexers and parsers generated by the ANTLR 4 tool. It enables Python applications to process structured text, validate input, and build abstract syntax trees (ASTs) for executing or translating languages. The current version is 4.13.2, with releases typically tied to the main ANTLR tool's irregular but generally annual or bi-annual update cycle.
pip install antlr4-python3-runtime Common errors
error ModuleNotFoundError: No module named 'antlr4' ↓
cause The 'antlr4' module is not installed in the Python environment.
fix
Install the module using pip: 'pip install antlr4-python3-runtime'.
error ImportError: No module named 'antlr4' ↓
cause The 'antlr4' module is not installed or not found in the Python path.
fix
Ensure the module is installed with 'pip install antlr4-python3-runtime' and that the Python path is correctly set.
error ERROR: No matching distribution found for antlr4-python3-runtime==4.8 ↓
cause The specified version of 'antlr4-python3-runtime' is not available for the current Python version or platform.
fix
Check the available versions and install a compatible one using 'pip install antlr4-python3-runtime'.
error Mismatched input '...' expecting '...' ↓
cause The input text being processed by the ANTLR parser does not conform to the grammar rules defined in your `.g4` files at the point where the error occurred.
fix
Review your grammar rules (
.g4 files) and the input string to ensure they are compatible. Adjust either the grammar or the input to match the expected structure, or implement a custom error strategy for more robust error handling. error AttributeError: 'str' object has no attribute 'getInputStream' ↓
cause You are attempting to pass a raw Python string directly to an ANTLR lexer or parser constructor that expects an ANTLR `InputStream` object.
fix
Wrap your input string in
antlr4.InputStream: input_stream = antlr4.InputStream(your_string) then pass input_stream to the lexer. Warnings
breaking ANTLR 4.10 and newer versions drop support for Python 3.5. Attempts to install or run the runtime on Python 3.5 will result in `SyntaxError` due to the use of f-strings in the codebase. ↓
fix Upgrade your Python environment to Python 3.6 or higher. For Python 3.5, you must pin the `antlr4-python3-runtime` version to `4.9.x` or earlier (e.g., `pip install antlr4-python3-runtime==4.9.3`).
gotcha The `antlr4-python3-runtime` package only provides the runtime libraries. To generate Python lexer/parser source files (`.py` files) from your `.g4` grammar, you *must* have a Java Runtime Environment (JRE) installed and download the ANTLR 4 tool (a `.jar` file). ↓
fix Install a JRE and download the `antlr-4.x.x-complete.jar` file from the official ANTLR website. Then use `java -jar antlr-4.x.x-complete.jar -Dlanguage=Python3 YourGrammar.g4` to generate the Python code before attempting to import it.
breaking A known issue existed in version 4.13.1 where the ANTLR runtime's internal version check might conflict with the version of the generated code, leading to runtime errors. ↓
fix Upgrade to `antlr4-python3-runtime==4.13.2` or later to resolve this specific version disagreement. Always ensure your ANTLR tool version matches your runtime version as closely as possible.
gotcha Care must be taken when choosing input streams. For string input, `InputStream` is generally used. For file input, `FileStream` is suitable. For reading from `sys.stdin`, `StdinStream` is available. Mismatching can lead to unexpected behavior or errors. ↓
fix Select the appropriate input stream class based on your data source: `InputStream(text)` for strings, `FileStream(filepath)` for files, and `StdinStream()` for standard input.
gotcha ANTLR 4 provides both Listener and Visitor patterns for traversing parse trees. Listeners are event-driven and perform an LR traversal, calling `enter` and `exit` methods. Visitors offer more control by explicitly requiring you to call `visit()` methods, making them more flexible for complex tree manipulations. ↓
fix Understand the differences between Listeners (generated with `-listener`) and Visitors (generated with `-visitor`) and choose the pattern that best suits your parse tree processing needs. When using Visitors, remember to explicitly call `visit()` on child nodes if you want to traverse them.
breaking The parser returned a `None` parse tree, leading to `AttributeError: 'NoneType' object has no attribute 'toStringTree'`. This typically occurs when the input string does not conform to the grammar's rules, especially the entry rule, or if the parser encountered unrecoverable syntax errors. ↓
fix Ensure your input string strictly adheres to the defined grammar rules. Specifically, check that the input matches the entry rule you are invoking on the parser (e.g., `parser.myEntryRule()`). You may also want to implement a custom `ErrorListener` to get more detailed feedback on parsing errors.
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.03s 18.8M
3.10 alpine (musl) - - 0.03s 18.8M
3.10 slim (glibc) wheel 1.5s 0.02s 19M
3.10 slim (glibc) - - 0.02s 19M
3.11 alpine (musl) wheel - 0.05s 20.8M
3.11 alpine (musl) - - 0.06s 20.8M
3.11 slim (glibc) wheel 1.7s 0.04s 21M
3.11 slim (glibc) - - 0.04s 21M
3.12 alpine (musl) wheel - 0.04s 12.7M
3.12 alpine (musl) - - 0.04s 12.7M
3.12 slim (glibc) wheel 1.4s 0.04s 13M
3.12 slim (glibc) - - 0.04s 13M
3.13 alpine (musl) wheel - 0.04s 12.4M
3.13 alpine (musl) - - 0.04s 12.3M
3.13 slim (glibc) wheel 1.5s 0.03s 13M
3.13 slim (glibc) - - 0.03s 13M
3.9 alpine (musl) wheel - 0.04s 18.3M
3.9 alpine (musl) - - 0.03s 18.3M
3.9 slim (glibc) wheel 1.8s 0.03s 19M
3.9 slim (glibc) - - 0.03s 19M
Imports
- InputStream, CommonTokenStream, Lexer, Parser, ParseTreeWalker, ParserRuleContext wrong
import antlr4correctfrom antlr4 import InputStream, CommonTokenStream from MyGrammarLexer import MyGrammarLexer # Assumes MyGrammar.g4 was compiled from MyGrammarParser import MyGrammarParser # Assumes MyGrammar.g4 was compiled from MyGrammarListener import MyGrammarListener # For listener pattern
Quickstart stale last tested: 2026-04-23
import os
from antlr4 import InputStream, CommonTokenStream, ParseTreeWalker
# --- BEGIN: Dummy generated classes for demonstration ---
# In a real scenario, these would be generated by the ANTLR tool:
# java -jar antlr-4.x.x-complete.jar -Dlanguage=Python3 MyGrammar.g4
class MyGrammarLexer:
def __init__(self, input_stream): pass
def getAllTokens(self): return []
class MyGrammarParser:
def __init__(self, token_stream): pass
def startRule(self): return None # Replace 'startRule' with your grammar's entry rule
class MyGrammarListener:
def enterEveryRule(self, ctx): pass
def exitEveryRule(self, ctx): pass
# ... other enter/exit methods for your grammar rules
# --- END: Dummy generated classes ---
# Assuming MyGrammar.g4 contains:
# grammar MyGrammar;
# startRule: 'hello' ID EOF;
# ID: [a-zA-Z]+;
# WS: [ \t\r\n]+ -> skip;
def parse_input(text):
input_stream = InputStream(text)
lexer = MyGrammarLexer(input_stream) # Use your generated Lexer class
stream = CommonTokenStream(lexer)
parser = MyGrammarParser(stream) # Use your generated Parser class
# Optionally, set up error handling
# parser.removeErrorListeners()
# parser.addErrorListener(MyCustomErrorListener())
tree = parser.startRule() # Call the entry rule of your grammar
# Optionally, walk the parse tree with a listener or visitor
# walker = ParseTreeWalker()
# listener = MyGrammarListener() # Use your generated Listener/Visitor class
# walker.walk(listener, tree)
print(f"Parse tree: {tree.toStringTree(recog=parser)}")
if __name__ == '__main__':
# Simulate user input or a file content
# For a real application, you might read from stdin or a file
test_input = os.environ.get('ANTLR_TEST_INPUT', 'hello world')
print(f"Parsing: '{test_input}'")
parse_input(test_input)
print("Note: In a real scenario, 'MyGrammarLexer' and 'MyGrammarParser' would be generated .py files from your .g4 grammar using the ANTLR Java tool.")