这行代码在PyPy中失败:
expr.__repr__ = lambda self: ast.dump(self, annotate_fields=False)
TypeError: can't set attributes on type object 'expr'
即使它在普通python中运行良好,即它给我的AST节点一个明智的__repr__
。有什么理由说它在PyPy中不起作用,有什么方法可以解决它吗?我试图修补repr
功能本身已经失败了。
不幸的是,没有简单的方法。在PyPy上,AST类的行为类似于list
或int
等内置类型,因为你无法改变它们。如果要定义自定义repr,您可以做的最好的事情就是定义自己的函数。您可能会发现ast.NodeVisitor
类可以方便地实现这样的功能。
只是为了记录,我测试了禁果,在python 3.6.6上添加一个方法到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'