Search code examples
pythondata-structuresmonkeypatchingpypy

PyPy: can't monkeypatch ast classes?


This line of code fails in PyPy:

expr.__repr__ = lambda self: ast.dump(self, annotate_fields=False)
TypeError: can't set attributes on type object 'expr'

even though it works great in normal python, i.e. it gives my AST nodes a sensible __repr__. Is there any reason why it doesn't work in PyPy, and is there any way to work around it? My attempts to monkey-patch the repr function itself have met with failure.


Solution

  • Unfortunately, there is no easy way. On PyPy, AST classes act like builtin types like list or int in that you can't alter them. If you want to define a custom repr, about the best you can do is define your own function. You may find the ast.NodeVisitor class handy for implementing such a function.