PyPy:不能monkeypatch ast类?

问题描述 投票:1回答:2

这行代码在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功能本身已经失败了。

python data-structures monkeypatching pypy
2个回答
2
投票

不幸的是,没有简单的方法。在PyPy上,AST类的行为类似于listint等内置类型,因为你无法改变它们。如果要定义自定义repr,您可以做的最好的事情就是定义自己的函数。您可能会发现ast.NodeVisitor类可以方便地实现这样的功能。


0
投票

只是为了记录,我测试了禁果,在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'
© www.soinside.com 2019 - 2024. All rights reserved.