有没有办法来防止python中的副作用? [英] is there any way to prevent side effects in python?

查看:103
本文介绍了有没有办法来防止python中的副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以防止python中的副作用?例如,下面的函数有副作用,是否有任何关键字或任何其他方式让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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆