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.

Était-ce utile?

La 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.

Autres conseils

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'
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top