Re: [Newbie] Referring to a global variable inside a function
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: [Newbie] Referring to a global variable inside a function

From: bruno at modulix <onurb@xiludom.gro>
Date: Mon Apr 10 2006 - 11:58:10 CEST

Ernesto García García wrote:
> Hi experts,
>
> I've built a class for parsing a user-defined list of files and matching
> lines with a user-defined list of regular expressions. It looks like this:
>
(snip code)
>
> But then, when I try to use my class using actions with "memory" it will
> fail:
>
> <code>
> import LineMatcher
>
> global count
> count = 0
>
> def line_action(line, match_dictionary):
> count = count + 1
(snip)
> </code>
>
> The error is:
> <console>
(snip)
> UnboundLocalError: local variable 'count' referenced before assignment
> </console>
>
> How would you do this?

FWIW, I would *not* use a global.

class LineAction(object):
  def __init__(self):
    self.count = 0

  def __call__(self, line, match_dictionary):
    self.count +=1

line_action = LineAction()

line_matcher = LineMatcher.LineMatcher()
line_matcher.add_files('*')
line_matcher.add_action(r'(?P<line>.*)', line_action)
line_matcher.go()

HTH

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
Received on Sun Apr 30 22:41:12 2006