Python PyPy:can';monkeypatch ast课程?

Python PyPy:can';monkeypatch ast课程?,python,data-structures,monkeypatching,pypy,Python,Data Structures,Monkeypatching,Pypy,这行代码在PyPy中失败: expr.__repr__ = lambda self: ast.dump(self, annotate_fields=False) TypeError: can't set attributes on type object 'expr' 尽管它在普通python中工作得很好,也就是说,它给我的AST节点提供了一个合理的\uuu repr\uu。有没有任何理由说明它在PyPy中不起作用,有没有办法解决它?我试图对repr函数本身进行猴子补丁的尝试失败了。不幸的是,

这行代码在PyPy中失败:

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

尽管它在普通python中工作得很好,也就是说,它给我的AST节点提供了一个合理的
\uuu repr\uu
。有没有任何理由说明它在PyPy中不起作用,有没有办法解决它?我试图对
repr
函数本身进行猴子补丁的尝试失败了。

不幸的是,没有简单的方法。在PyPy上,AST类的行为类似于内置类型,如
list
int
,因为您不能修改它们。如果要定义自定义repr,最好是定义自己的函数。您可能会发现
ast.NodeVisitor
类对于实现这样一个函数非常方便。

为了记录在案,我在cpython 3.6.6上测试了forbiddenfruit以向int添加一个方法,它起到了作用:

$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'

... 可能有用。。。尽管它可能不适用于repr…@JoranBeasley(来自该页面):“因为禁果从根本上依赖于C API,所以该库不会适用于其他python实现,如Jython、PyPy等。”哦,你的权利。。。抱歉…错过了:(