Emulating pass-by-value behaviour in python
Question: I would like to emulate the pass-by-value behaviour in python. In other words,
I would like to make absolutely sure that the function I write do not modify
user supplied data.

One possible way is to use deep copy:

    
    
    from copy import deepcopy
    def f(data):
        data = deepcopy(data)
        #do stuff
    

is there more efficient or more _pythonic_ way to achieve this goal, making as
few assumptions as possible about the object being passed (such as .clone()
method)

**Edit**

I'm aware that technically everything in python is passed by value. I was
interested in _emulating_ the behaviour, i.e. making sure I don't mess with
the data that was passed to the function. I guess the most general way is to
clone the object in question either with its own clone mechanism or with
deepcopy.


Answer: You can make a decorator and put the cloning behaviour in that.

    
    
    >>> def passbyval(func):
    def new(*args):
    	cargs = [deepcopy(arg) for arg in args]
    	return func(*cargs)
    return new
    
    >>> @passbyval
    def myfunc(a):
        print a
    
    >>> myfunc(20)
    20
    

This is not the most robust way, and doesn't handle key-value arguments or
class methods (lack of self argument), but you get the picture.

Note that the following statements are equal:

    
    
    @somedecorator
    def func1(): pass
    # ... same as ...
    def func2(): pass
    func2 = somedecorator(func2)
    

You could even have the decorator take some kind of function that does the
cloning and thus allowing the user of the decorator to decide the cloning
strategy. In that case the decorator is probably best implemented as a class
with `__call__` overridden.

