Enforcing side effects in python

放肆的年华 提交于 2019-12-10 14:59:00

问题


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 ?


回答1:


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 + 1

The 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
1

Though the function f looks pure, the add operation on x has the side-effect of incrementing s.



来源:https://stackoverflow.com/questions/10509916/enforcing-side-effects-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!