Q: Why does this work???

Neal Norwitz neal at metaslash.com
Sun Jul 14 22:23:23 EDT 2002


On Sun, 14 Jul 2002 21:05:03 -0400, Jim Cerra wrote:

> I'm very new to Python, and I've been examing a bit of code... I can't
> figure out why the following doesn't produce an error:
> 
> import string
> 
> total_hits   = 0
> hits_by_page = {}  # maps document URL to hit count for that document
>
> def process_request(host, date, timezone, method, url, protocol, code,
> bytes):
>     global total_hits
>     total_hits = total_hits + 1
> 
>     if hits_by_page.has_key(url):
>         hits_by_page[url] = hits_by_page[url] + 1
>     else:
>         hits_by_page[url] = 1
> 
> In the function, process_request(), why isn't the variable,
> hits_by_page, declared as a global var?  I tried putting in that code ("
>    global hits_by_page") and there is no effect.  The script still
> works.
> 
> My question is Why???

You need to declare total_hits global because you rebind 
(assign, hint the equals sign).  But hits_by_page is not
assigned to.  The dictionary is changed, but not rebound.
If you wanted to set hits_by_page to a new dictionary,
you would need to declare it global.

The rule is that if you do an assignment, you must declare
the variable global.  If you are only referencing the
variable, it does not need to be declared global.

See faq #4.36 - http://www.python.org/cgi-bin/faqw.py?req=all#4.36

Neal



More information about the Python-list mailing list