Why don't my global variables work?

Nathan J Froyd froydnj at cs.rose-hulman.edu
Wed Jun 16 16:41:14 EDT 1999


Can somebody explain this point to me? I have the following program
(posted below to avoid disturbing the continuity):

It's a program for turning a netscape bookmarks file into something
resembling XML. Anyway, you might be puzzled about the evilcount
parameter in topic_read(). If I remove the line `count = evilcount',
python gives up, complaining about a NameError. I know darn well count
already exists, so what is the problem? Especially when a similar
program works as well. (similar program follows)

#!/usr/local/bin/python

count = 0

def evilfunc(num):
	print " " * count, "iamevil"

for x in xrange(0, 100):
	evilfunc(count)
	count = x

Could somebody look at this, perhaps running the program and explain
to me what fundamental fact I am missing here? Because it looks like
my program should run without errors. Thanks!

Nathan

#!/usr/local/bin/python

import sys
import re
import string

titleregex = "<TITLE>(.*)</TITLE>"

topicheadregex = "<DT><H3 [^>]*>([^<]*)</H3>$"
bookmarkregex = "<DT><A HREF=\"([^\"]*)\" .*>([^<]*)</A>$"
topicendregex = "</DL>.*"

# I HAVE DEFINED `count' HERE, PYTHON!
count = 0

ctopic = re.compile(topicheadregex)
cbookmark = re.compile(bookmarkregex)
cend = re.compile(topicendregex)

bmarkfile = open(sys.argv[1], 'r')
print count

def topic_read(regmatch, evilcount):
  # if you comment this line, the program will not work
  count = evilcount
  print "\t" * count, "<topic name=\"%s\">" % regmatch.group(1)
  count = count + 1

  while 1:
    tline = bmarkfile.readline()
    tline = string.strip(tline)

    tmatch = ctopic.match(tline) # first try seeing if we have new topics

    if tmatch is not None:
      topic_read(tmatch, count)

    tmatch = cend.match(tline) # now try checking for </topic>

    if tmatch is not None:
      count = count - 1
      print "\t" * count, "</topic>"
      return # we finished our topic call

    tmatch = cbookmark.match(tline)

    if tmatch is not None:
      print "\t" * count, "<bookmark link=\"%s\">%s</bookmark>" % (tmatch.group(1), tmatch.group(2))

while 1:
  count = 0
  line = bmarkfile.readline()

  if line is None:
    break

  line = string.strip(line)
  match = cbookmark.match(line)

  if match is not None:
    # this is always as the top level, so we don't worry about topiccount
    print "<bookmark link=\"%s\">%s</bookmark>" % (match.group(1), match.group(2))
    continue

  match = ctopic.match(line)

  if match is not None:
    topic_read(match, count)

sys.exit(0)





More information about the Python-list mailing list