0

This appeared as some test question. If you consider this function which uses a cache argument as the 1st argument

def f(cache, key, val): 
    cache[key] = val
    # insert some insanely complicated operation on the cache
    print cache

and now create a dictionary and use the function like so:

c = {}
f(c,"one",1)
f(c,"two",2)

this seems to work as expected (i.e adding to the c dictionary), but is it actually passing that reference or is it doing some inefficient copy ?

17
  • 2
    possible duplicate of Python: How do I pass a variable by reference? Commented May 8, 2012 at 6:19
  • not exactly sure what you mean but python doesn't make copies unless you explicitly tell it to by using the copy module. Commented May 8, 2012 at 6:19
  • Is your question about whether the integer values that you are passing to f are passed by reference or by value? Commented May 8, 2012 at 6:19
  • 1
    @PeterMoore I think the accepted answer on that question listed above will answer the question I think you are asking. If it doesn't, then please specify what the confusing part is. I think the cache bit is a red herring. Commented May 8, 2012 at 6:32
  • 1
    All arguments in Python are passed by reference, so, yes, c is passed by reference. Commented May 8, 2012 at 6:44

1 Answer 1

1

The dictionary passed to cache is not copied. As long as the cache variable is not rebound inside the function, it stays the same object, and modifications to the dictionary it refers to will affect the dictionary outside.

There is not even any need to return cache in this case (and indeed the sample code does not).

It might be better if f was a method on a dictionary-like object, to make this more conceptually clear.

If you use the id() function (built-in, does not need to be imported) you can get a unique identifier for any object. You can use that to confirm that you are really and truly dealing with the same object and not any sort of copy.

Sign up to request clarification or add additional context in comments.

1 Comment

i see. yep i tested it and found that using a global to be a little faster (as expected) but only be 1 thenth of a second on 10 million iterations. Thanks for the reassurance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.