本文介绍了在Python中强化副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种工具可以让您将函数/方法注释为纯,然后分析代码以测试所述函数/方法是否无副作用?
解决方案在Python世界中,这个问题没有什么意义,因为对象对函数中发生的事情有如此多的发言权
例如,你如何判断下面的函数是纯的?
def f(x): return x + 1答案取决于 x 是什么:
>>> class A(int): def __add __(self,other): global s s + = 1 return int .__ add __(self,other) >>> def f(x): return x + 1 >>> s = 0 >>> f(A(1)) 2 >>> s 1尽管函数 f 看起来很纯,但在 x 上添加操作具有增加 s 的副作用。
Is there a tool that enables you to annotate functions/methods as "pure" and then analyzes the code to test if said functions/methods are side effect free ?
解决方案In the Python world, the question doesn't make much sense since objects have so much say in what happens in a function call.
For example, how could you tell if the following function is pure?
def f(x): return x + 1The answer depends on what x is:
>>> class A(int): def __add__(self, other): global s s += 1 return int.__add__(self, other) >>> def f(x): return x + 1 >>> s = 0 >>> f(A(1)) 2 >>> s 1Though the function f looks pure, the add operation on x has the side-effect of incrementing s.
更多推荐
在Python中强化副作用
发布评论