有没有办法来防止python中的副作用? [英] is there any way to prevent side effects in python?
问题描述
def func_with_side_affect(a):
a.append('foo')
Python确实没有设置来强制防止副作用。正如其他人提到的那样,您可以尝试 deepcopy
数据或使用不可变类型,但这些类型仍然存在棘手的边角情况,而且只需要花费更多的精力比它的价值更高。
在Python中使用函数式风格通常涉及程序员简单地将其功能设计为功能性。换句话说,无论何时你写一个函数,你写它的方式不会改变参数。
如果您打电话给其他人的功能,那么您必须确保您传递的数据不能突变,否则 必须保留围绕一个安全的,未触及的数据副本,您远离那个不受信任的函数。
Is there any way to prevent side effects in python? For example, the following function has a side effect, is there any keyword or any other way to have the python complain about it?
def func_with_side_affect(a):
a.append('foo')
Python is really not set up to enforce prevention of side-effects. As some others have mentioned, you can try to deepcopy
the data or use immutable types, but these still have corner cases that are tricky to catch, and it's just a ton more effort than it's worth.
Using a functional style in Python normally involves the programmer simply designing their functions to be functional. In other words, whenever you write a function, you write it in such a way that it doesn't mutate the arguments.
If you're calling someone else's function, then you have to make sure the data you are passing in either cannot be mutated, or you have to keep around a safe, untouched copy of the data yourself, that you keep away from that untrusted function.
这篇关于有没有办法来防止python中的副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!