scope of function parameters (take two)
Daniel Kluev
dan.kluev at gmail.com
Tue May 31 03:38:40 EDT 2011
On Tue, May 31, 2011 at 6:17 PM, Henry Olders <henry.olders at mcgill.ca> wrote:
> Clearly, making a copy within the function eliminates the possibility of the
> side effects caused by passing in mutable objects. Would having the
> compiler/interpreter do this automatically make python so much different?
As I've pointed, you can make decorator to do that. Adding @copy_args
to each function you intend to be pure is not that hard.
import decorator
import copy
@decorator.decorator
def copy_args(f, *args, **kw):
nargs = []
for arg in args:
nargs.append(copy.deepcopy(arg))
nkw = {}
for k,v in kw.iteritems():
nkw[k] = copy.deepcopy(v)
return f(*nargs, **nkw)
@copy_args
def test(a):
a.append(1)
return a
>>> l = [0]
>>> test(l)
[0, 1]
>>> l
[0]
>>> inspect.getargspec(test)
ArgSpec(args=['a'], varargs=None, keywords=None, defaults=None)
So this decorator achieves needed result and preserves function signatures.
--
With best regards,
Daniel Kluev
More information about the Python-list
mailing list