newbie 'Find File' question.

Jeff Shannon jeff at ccvcorp.com
Wed Aug 1 12:43:14 EDT 2001


"G. Willoughby" wrote:

> very useful ta, maybe you could help me with a little problem, my code:

[cleaning up indentation...]

>
> def go():
>     status.set("Searching...")
>
>     if checkEntryField() == 1:
>
>     resultPane.delete(0, END) # Clear the results pane!
>     searchString=str(entryField.get()) # Get search string
>
>     def search(of, dir, files):
>         for file in files:
>         if file == searchString:
>             of.insert(END, os.path.join(dir, file))
>
>     driveList=string.split(win32api.GetLogicalDriveStrings(),'\0')[:-1] # Get
> Drives
>     for x in range(0,len(driveList)):
>         os.path.walk(driveList[x], search, resultPane)
>     status.set("Done")

I'm guessing at the correct indentation of these last few lines.

> when this script is run i get this error:
>
> Local name 'searchString' in 'go' shadows use of 'searchString' as global in
> nested scope 'search' def go()
>

What's happening, is that you have a nested function (search) that is using a
variable defined in its parent scope.  Python's old scoping rules don't have the
behavior you're looking for--it looks for a value of searchString in three
scopes--that of search(), the global scope (module level), and builtins.
searchString is not defined at any of those levels, but it *is* defined in
go().  If you do indeed want to use the searchString from go() within the nested
function search(), then you need to use Python's *new* scoping rules--nested
scopes.  These rules are available starting with Python 2.1, which you obviously
have or you wouldn't be getting that warning.  However, these rules are not the
default--in order to activate them, you need the first line in your script to
be:

from __future__ import nested_scopes

Then everything should run as you intend.
Hope that helps...

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list