Skip to content Skip to sidebar Skip to footer

Python Elements Retrieved From Container (list, Dict, Tuple Etc) Passed By Reference Or Value?

I have a function that updates data in a cache (implemented as a dictionary). def updateCache(name, new_data): global cache info = cache[name] # is this being passed to me

Solution 1:

Let's just try this out, shall we:

defupdateCache(name, new_data):
    global cache
    info = cache[name]
    datarows = info['datarows']
    datarows.append(new_data)


cache = {'foo': {'datarows': []}, 'bar': {'datarows': []}}

print cache
updateCache('foo', 'bar')
print cache

outputs:

{'foo': {'datarows': []}, 'bar': {'datarows': []}}
{'foo': {'datarows': ['bar']}, 'bar': {'datarows': []}}

Solution 2:

or in other words, are the following statements redundant or required?

They are redundant, since almost everything in python is a reference. (Unless you don't play with some magic functions like __new__)

Solution 3:

There are actually three options. See this link for a description on the different copy flavors. See this post for a nice explanation for each of these.

  1. the variable info is a reference to the same dict object as cache[name]
  2. info holds a shallow copy of that dict
  3. info holds a deep copy of that dict

For the determination of which option applies in this case, you need to investigate the properties of your object. In this case you have a mutable container object (dict). Which implies that you assign the object reference to the new name, as in (equivalent to c = d = {}):

(Note that c = d = [] assigns the same object to both c and d.)

Solution 4:

info has a value assigned to it. A quick experiment in a Python command line will confirm:

>>>cache = {'ProfSmiles':'LikesPython'}>>>name = 'ProfSmiles'>>>cache[name]
'LikesPython'

therefore in this case if we did info = cache[name], then type(info) would evaluate to <type 'str'> So yes, the last two lines are redundant

Solution 5:

As this answer to a related question explains:

  1. All variables contain references to an object
  2. All parameters receive references that are passed by value
  3. Changes will have an effect in the outside world only when a mutable object state is modified

Hence, what has to be taken into account is when some statement changes the state of an object or creates a new one.

Post a Comment for "Python Elements Retrieved From Container (list, Dict, Tuple Etc) Passed By Reference Or Value?"