Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #6715
| References | <F8395F78-615E-4FBD-B6FC-1D6173EAEA45@mcgill.ca> <F4EAD1ED-563D-4D6E-A50C-68308A9F26B7@mcgill.ca> <BANLkTin5exEpDkE3on3BAaWwHOjpg_vC8g@mail.gmail.com> <6699AB10-988A-49AD-B7C1-6BAA2CC3D008@mcgill.ca> |
|---|---|
| Date | 2011-05-31 18:38 +1100 |
| Subject | Re: scope of function parameters (take two) |
| From | Daniel Kluev <dan.kluev@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2309.1306827523.9059.python-list@python.org> (permalink) |
On Tue, May 31, 2011 at 6:17 PM, Henry Olders <henry.olders@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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: scope of function parameters (take two) Daniel Kluev <dan.kluev@gmail.com> - 2011-05-31 18:38 +1100
csiph-web