local variable referenced before assignment

Alf P. Steinbach alfps at start.no
Sun Apr 4 18:22:48 EDT 2010


* johngilbrough:
> I cannot make sense of what's happening here ...  I'm getting the
> following error:
> 
> initializing last modified time
> /home/john/Dropbox/Projects/python/scripts/src 29
> referencing last modified time
> /home/john/Dropbox/Projects/python/scripts/src 29
> referencing last modified time
> Traceback (most recent call last):
>   File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
> line 42, in <module>
>     time.sleep(10000)
>   File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
> line 18, in handler
>     if modifiedTime <> lastModifiedTime:
> UnboundLocalError: local variable 'lastModifiedTime' referenced before
> assignment
> 
> From this logic:
> 
> #!/usr/bin/python
> def watchFile(filePath, callback):
>     ###
>     #   calls callback whenever file is changed
>     ###
>     import fcntl
>     import os
>     import signal
>     print "initializing last modified time"
>     lastModifiedTime = os.path.getmtime(filePath)
> 
>     def handler(signum, frame):
>         ## this gets called twice whenever a file changes
>         print filePath + " " + str(signum)
>         modifiedTime = os.path.getmtime(filePath)
>         print "referencing last modified time"
>         if modifiedTime <> lastModifiedTime:
>             lastModifiedTime = modifiedTime
>             callback()

Since 'handler' has an assignment to 'lastModifiedTime' that name becomes the 
name of a local variable. It's not the execution of the assignment that creates 
the variable. It's the /presence/ of the assignment (this helps the compiler 
generate code that allocates all local variables on entry to the function).

There are a couple of ways around.

(1)
At least in Py3 you can declare the variable as 'global', like this:

    global lastModifiedTime

within the function.

(2)
Or, you can apply some indirection, which is nearly always a solution to any 
computer science and programming problem, and declare your variable like so:

    class Object: pass

    g = Object()
    g.lastModifiedTime = os.path.getmtime( filePath )

Then when you assign to 'g.lastModifiedTime' in 'handler' you're not creating a 
variable, because you're assigning to an attribute of an object.

(3)
Best is however to recognize that you have some state (your variable) and some 
operations on that state (your callback), and that that is what objects are all 
about. I.e. wrap your logic in a class. Then 'lastModifiedTime' becomes an 
instance attribute, and 'handler' becomes a method.

It doesn't matter that there will only ever be one object (instance) of that class.

Classes were meant for just this sort of thing, state + operations.


Cheers & hth.,

- Alf




More information about the Python-list mailing list