Question

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.

Was it helpful?

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.

OTHER TIPS

Just for the record, I tested forbiddenfruit to add a method to int on cpython 3.6.6 and it worked:

$ipython
Python 3.6.6 (default, Jul 21 2018, 02:39:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from forbiddenfruit import curse

In [2]: curse(int, 'test', lambda self: 'hi')

In [3]: (1).test()
Out[3]: 'hi'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top