这行代码在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
函数本身进行修补已经失败了。
答案 0 :(得分:2)
不幸的是,没有简单的方法。在PyPy上,AST类的行为类似于内置类型,如list
或int
,因为您无法改变它们。如果要定义自定义repr,您可以做的最好的事情就是定义自己的函数。您可以找到ast.NodeVisitor
类来实现这样的功能。
答案 1 :(得分:0)
仅作记录,我测试了禁果,以便在cpython 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'