~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Quick Python: Copy Decorator

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

If you want to guarantee that your function doesn’t modify any of the references and don’t mind paying a price in memory consumption, here is a decorator you can easily add to your functions.

from copy import deepcopy
def copy_arguments(func):
    def wrapper(*args, **kwargs):
        new_args = deepcopy(args)
        new_kwargs = deepcopy(kwargs)
        return func(*new_args, **new_kwargs)
    return wrapper

Example usage:

@copy_arguments
def modify1(xs):
    for i, _ in enumerate(xs):
        xs[i] *= 2

Comparison:

def modify2(xs):
    for i, _ in enumerate(xs):
        xs[i] *= 2

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
modify1(a)
modify2(a)
print(a)
print(b)
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :