views:

27

answers:

1

Not sure of the terminology here, but this would be difference between eq? and equal? in scheme, or the difference between == and strncmp with C strings; where in each case the first would return false for two different strings that actually have the same content and the second would return true.

I'm looking for the latter operation, for Python's ASTs.

Right now, I'm doing this:

import ast
def AST_eq(a, b):
    return ast.dump(a) == ast.dump(b)

which apparently works but feels like a disaster waiting to happen. Anyone know of a better way?

Edit: unfortunately, when I go to compare the two ASTs' __dict__'s, that comparison defaults to using the individual elements' __eq__ methods. ASTs are implemented as trees of other ASTs, and their __eq__ apparently checks for reference identity. So neither straight == nor the solution in Thomas's link work. (Besides which, I also don't want to subclass every AST node type to insert this custom __eq__.)

A: 

In Python, object identitiy is compared using the is operator (which, unlike ==, cannot be overloaded). Unless implemented by a moron, == will not compare identity, but rather equality (if possible and implemented, of course). And in case of the built-in string class, this is certainly not the case.

There may be another problem with your implementation, though - as dump produces very precise information (suitable for debugging), two asts with e.g. a variable named differently may be considered !=. This may or may not be what you want.

delnan
That sort of precision is actually what I want, since I am working on a domain-specific language whose interpreter rewrites it to standard python.
Wang