[Tutor] would someone please explain this concept to me

Steven D'Aprano steve at pearwood.info
Tue Jun 4 21:08:17 EDT 2019


On Tue, Jun 04, 2019 at 11:37:23PM +0000, nathan tech wrote:

> globals.py:
> 
> feeds={}
> blank_feed={}
> blank_feed["checked"]=1
> blank_feed["feed"]=0

That is more easily, and better, written as:

feeds = {}
blank_feed = {"checked": 1, "feed": 0}


> main file:
> 
> import globals as g
> # some code that loads a feed into the variable knm

Do you mean something like this? If so, you should say so.

knm = "some feed"


> g.feeds[link]=g.blank_feed;

What's "link" here? And there is no need for the semi-colon.

> g.feeds[link]["feed"]=knm

Right... what the above line does is *precisely* the same as 

g.blank_feed["feed"] = knm

Follow the program logic. I'm inserting 1970s BASIC style line numbers 
to make it easier to discuss the code, remember that you can't actually 
do that in Python.

10: g.feeds[link] = g.blank_feed
20: g.feeds[link]["feed"] = knm

Line 10 sets g.feeds[link] to the dict "blank_feed". *Not* a copy: you 
now have two ways of referring to the same dict:

    "g.blank_feed" and "g.feeds[link]"

both refer to the one dict, just as "Nathan" and "Mr Tech" are two ways 
of referring to the same person (you).

So line 20 does this:

    - look for the name "g", which gives the "globals.py" module;

    - inside that module, look for the name "feeds", which gives
      the "feeds" dict;

    - look inside that dict for the key "link" (whatever value
      that currently holds), which by line 10 has been set to
      the same dict "blank_feed".

    - inside the blank_feed dict, set key "feed" to "knm".



> #in the below code, the variable link has a different value:
> # load a feed into the variable r

Something like this?

r = "a different feed"

> g.feeds[link]=g.blank_feed

Now you have *three* ways of naming the same dict:

    "g.blank_feed", "g.feeds[link]", "g.feeds[different_link]"

but they all point to the same dict.

> g.feeds[link]["feed"]=r
> 
> 
> Now at this point, python would set the first loaded feed to the same 
> thing as the second loaded feed. It also set g.blank_feed to the second 
> feed, as well.

No, there is only one feed in total. You just keep updating the same 
feed under different names.


> I replaced the last three lines with this:
> 
> # load a feed into the variable r
> g.feeds[link]=g.blank_feed;
> g.feeds[link]["feed"]=r
> 
> And it works.

I don't see any difference between the replacement code and the original 
code. The code you show does exactly the same thing.


> but why does it work?
> 
> Why does that semi unlink all the variables?

Semi-colon?

It doesn't. You must have made other changes as well, semi-colons don't 
have any runtime effect. They are *purely* syntax to tell the parser to 
seperate multiple statements on one line.


-- 
Steven


More information about the Tutor mailing list