[Newbie] Referring to a global variable inside a function

Fredrik Lundh fredrik at pythonware.com
Sun Apr 9 06:47:09 EDT 2006


Ernesto García García wrote:

> 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
>
> line_matcher = LineMatcher.LineMatcher()
> line_matcher.add_files('*')
> line_matcher.add_action(r'(?P<line>.*)', line_action)
> line_matcher.go()
> </code>
>
> The error is:
> <console>
> Traceback (most recent call last):
>    File "Test.py", line 12, in ?
>      line_matcher.go()
>    File "LineMatcher.py", line 21, in go
>      action(line, match.groupdict())
>    File "Test.py", line 7, in line_action
>      count = count + 1
> UnboundLocalError: local variable 'count' referenced before assignment
> </console>
>
> How would you do this?

    def line_action(line, match_dictionary):
        global count # make it a module-global variable, not a function-local
        count = count + 1

</F>






More information about the Python-list mailing list