Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6715 > unrolled thread

Re: scope of function parameters (take two)

Started byDaniel Kluev <dan.kluev@gmail.com>
First post2011-05-31 18:38 +1100
Last post2011-05-31 18:38 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: scope of function parameters (take two) Daniel Kluev <dan.kluev@gmail.com> - 2011-05-31 18:38 +1100

#6715 — Re: scope of function parameters (take two)

FromDaniel Kluev <dan.kluev@gmail.com>
Date2011-05-31 18:38 +1100
SubjectRe: scope of function parameters (take two)
Message-ID<mailman.2309.1306827523.9059.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web