Peter Moore
Peter Moore

Reputation: 2086

cache in python function

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 ?

Upvotes: 0

Views: 421

Answers (1)

Andrew Gorcester
Andrew Gorcester

Reputation: 19953

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.

Upvotes: 1

Related Questions