is there any way to prevent side effects in python?

后端 未结 7 2025
别跟我提以往
别跟我提以往 2021-02-05 15:14

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 abou

7条回答
  •  后悔当初
    2021-02-05 15:49

    You'll have to make a copy of the list first. Something like this:

    def func_without_side_affect(a):
        b = a[:]
        b.append('foo')
        return b
    

    This shorter version might work for you too:

    def func_without_side_affect(a):
        return a[:] + ['foo']
    

    If you have nested lists or other things like that, you'll probably want to look at copy.deepcopy to make the copy instead of the [:] slice operator.

提交回复
热议问题