Pass list to function by value

后端 未结 4 1689
南旧
南旧 2020-12-06 18:24

I want to pass a list into function by value. By default, lists and other complex objects passed to function by reference. Here is some desision:

def add_at_         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 18:58

    This might be an interesting use case for a decorator function. Something like this:

    def pass_by_value(f):
        def _f(*args, **kwargs):
            args_copied = copy.deepcopy(args)
            kwargs_copied = copy.deepcopy(kwargs)
            return f(*args_copied, **kwargs_copied)
        return _f
    

    pass_by_value takes a function f as input and creates a new function _f that deep-copies all its parameters and then passes them to the original function f.

    Usage:

    @pass_by_value
    def add_at_rank(ad, rank):
        ad.append(4)
        rank[3] = "bar"
        print "inside function", ad, rank
    
    a, r = [1,2,3], {1: "foo"}
    add_at_rank(a, r)
    print "outside function", a, r
    

    Output:

    "inside function [1, 2, 3, 4] {1: 'foo', 3: 'bar'}"
    "outside function [1, 2, 3] {1: 'foo'}"
    

提交回复
热议问题