Esprima Python
Esprima Python is a Python port of the Esprima ECMAScript parser. It provides an ECMAScript (JavaScript) parsing infrastructure for multipurpose analysis in Python, generating a syntax tree that adheres to the SpiderMonkey AST format. The current version is 4.0.1, with releases typically following updates to the upstream JavaScript Esprima project or significant internal Python improvements.
Warnings
- breaking Major API changes occurred between version 3.x and 4.x. If upgrading from an older major version, review the GitHub README for updated usage patterns. Direct migration without code changes is unlikely to work.
- breaking The `AST.to_json()` method was removed in version 4.0.0. Use `AST.to_dict()` instead for converting the AST object to a Python dictionary, which can then be serialized to JSON using Python's `json` module if needed.
- gotcha Esprima Python generates an AST that conforms to the SpiderMonkey Parser API's AST format for ECMAScript (JavaScript). This means the structure and node types in the resulting AST (e.g., from `tree.to_dict()`) will reflect JavaScript syntax, not Python's native AST or common Pythonic conventions. Users familiar with Python's `ast` module might find the structure different.
Install
-
pip install esprima
Imports
- parse
from esprima import parse
- EsprimaException
from esprima.error import EsprimaException
Quickstart
import esprima
js_code = "var answer = 42; console.log(answer);"
try:
# Parse the JavaScript code
tree = esprima.parse(js_code, options={'loc': True, 'range': True})
# The 'tree' object is an AST. It can be converted to a dictionary.
ast_dict = tree.to_dict()
# Print a part of the AST (e.g., the first statement's type)
if ast_dict and 'body' in ast_dict and len(ast_dict['body']) > 0:
print(f"Parsed statement type: {ast_dict['body'][0]['type']}")
# Example of accessing tokens (if options={'tokens': True} was used)
# tokens = esprima.tokenize(js_code)
# print(f"First token: {tokens[0].to_dict()}")
except esprima.error.EsprimaException as e:
print(f"Parsing error: {e}")