Python Glossary Русский

Python 3.14+astfunction

ast.compare()

helper functions

Recursively compares two ASTs by structure and field values. Tells whether two pieces of code are the same up to formatting. Added in 3.14.

Syntax

ast.compare(a, b, /, *, compare_attributes=False)

The == operator on nodes compares identity, so two identical parses give False; this function is what you need. By default positions (lineno, col_offset) are ignored, so 'x=1' equals 'x = 1 # c'; compare_attributes=True compares them too. Before 3.14 the same is done by comparing ast.dump() strings within one Python version.

Examples

# Python 3.14+
import ast
a = ast.parse('x=1')
b = ast.parse('x  =  1  # c')
print(a == b)  # → False
print(ast.compare(a, b))  # → True
print(ast.compare(a, b, compare_attributes=True))  # → False
import ast
a = ast.parse('x=1')
b = ast.parse('x  =  1  # c')
print(ast.dump(a) == ast.dump(b))  # → True — способ до 3.14

See also

Open in the full glossarydocs.python.orgReport an inaccuracy