python: unintentionally modifying parameters passed into a function

前端 未结 4 830
死守一世寂寞
死守一世寂寞 2021-02-04 10:05

A few times I accidentally modified the input to a function. Since Python has no constant references, I\'m wondering what coding techniques might help me avoid making this mista

4条回答
  •  醉话见心
    2021-02-04 10:50

    First general rule: don't modify containers: create new ones.

    So don't modify your incoming dictionary, create a new dictionary with a subset of the keys.

    self.fields = dict( key, value for key, value in fields.items()
                         if accept_key(key, data) )
    

    Such methods are typically slightly more efficient then going through and deleting the bad elements anyways. More generally, its often easier to avoid modifying objects and instead create new ones.

    Second general rule: don't modify containers after passing them off.

    You can't generally assume that containers to which you have passed data have made their own copies. As result, don't try to modify the containers you've given them. Any modifications should be done before handing off the data. Once you've passed the container to somebody else you are no longer the sole master of it.

    Third general rule: don't modify containers you didn't create.

    If you get passed some sort of container, you do not know who else might be using the container. So don't modify it. Either use the unmodified version or invoke rule1, creating a new container with the desired changes.

    Fourth general rule: (stolen from Ethan Furman)

    Some functions are supposed to modify the list. That is their job. If this is the case make that apparent in the function name (such as the list methods append and extend).

    Putting it all together:

    A piece of code should only modify a container when it is the only piece of code with access to that container.

提交回复
热议问题