Emulating pass-by-value behaviour in python

There is no pythonic way of doing this.

Python provides very few facilities for enforcing things such as private or read-only data. The pythonic philosophy is that “we’re all consenting adults”: in this case this means that “the function shouldn’t change the data” is part of the spec but not enforced in the code.


If you want to make a copy of the data, the closest you can get is your solution. But copy.deepcopy, besides being inefficient, also has caveats such as:

Because deep copy copies everything it may copy too much, e.g., administrative data structures that should be shared even between copies.

[…]

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types.

So i’d only recommend it if you know that you’re dealing with built-in Python types or your own objects (where you can customize copying behavior by defining the __copy__ / __deepcopy__ special methods, there’s no need to define your own clone() method).

Leave a Comment