[Tutor] Fwd: Re: would someone please explain this concept to me

Alan Gauld alan.gauld at yahoo.co.uk
Wed Jun 5 19:57:36 EDT 2019


On 05/06/2019 20:47, nathan tech wrote:

> so for example if I do:
> 
> feeds[feed1]["limit"]=g.checklimit
> 
> And later did g.checklimit=7000
> 
> Would it change feeds[feed1]["limit"] too?

No, because the feeds value is still referencing the
original value object. The issue arises when you modify a mutable
object that is references by two (or more) variables. If the value
is immutable then the references will retain the original value.

Specifically, in your case.
The first example you set the feeds value to a dictionary. Then you
modified the contents of the dictionary but did not change the
dictionary itself.

base_dict = {}   # create object
feeds['foo'] = base_dict   # reference to same dict object
base_dict['x'] = bar       # modified dict referred to by both variables


But in the second example you actially change the object
that checklimit refers to.

checklimit = 22   # immutable value assigned
feeds['bar'] = checklimit   # both refer to same immutable value
base_var = 66   # now feeds refers to original object: 22
                # and checklimit refers to new object: 66

In the first case you do not change the object that base_dict refers to,
you only change its content. In the second case you make checklimit
refer to a completely new object.

Does that make sense?

PS. Notice that the use of a globals module, g, is completely irrelevant
to this issue. It has nothing to do with the values being in a module,
the issue is purely about references to objects and whether you modify
the referenced object or its contents.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list