variable assignment within a loop

John Roth newsgroups at jhrothjr.com
Mon Nov 3 17:33:31 EST 2003


"hokieghal99" <hokiegal99 at hotmail.com> wrote in message
news:bo6ea9$c70$1 at solaris.cc.vt.edu...
> I have this for loop in a program that I'm writing:
>
>          for bad_dir_char in bad_dir_chars:
>              newdir = dir.replace(bad_dir_char,'-')
>
> Now, when I use this if statement:
>
>          if newdir != dir:
>              old_dir_path = os.path.join(root,dir)
>              new_dir_path = os.path.join(root,newdir)
>              os.rename(old_dir_path,new_dir_path)
>              print "replaced: ",bad_dir_char,"
>
> I get a "local variable 'newdir' referenced before assignment" error.
>
> I am somewhat new to programming and I do not understand a lot about
> where variables live and where they do not. I know the difference
> between global and function specific variables, but I was under the
> impression that if a local variable lived within a function that I could
> access its contents *anywhere* in that function. This is obviuously
> wrong, could someone expound upon this? Not that it matters, but below
> is the entire function that I'm playing with. I have a working version
> of it, but I'm cleaning it up a bit (I know that that is a bad thing,
> but it helps me learn more about programming).
>
> import os, re, string
> print
> setpath = raw_input("Path to the Directory to act on: ")
> def clean_names(setpath):
>      bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]') # bad characters
>      for root, dirs, files in os.walk(setpath):
>          for dir in dirs:
>              bad_dir_chars = bad.findall(dir)
>              for bad_dir_char in bad_dir_chars:
>                  newdir = dir.replace(bad_dir_char,'-')
>              if newdir != dir:
>                  old_dir_path = os.path.join(root,dir)
>                  new_dir_path = os.path.join(root,newdir)
>                  os.rename(old_dir_path,new_dir_path)
>                  print "replaced: ",bad_dir_char," in dir ",dir," ",
>

Your problem is because Python has a bit of a split personality
about local variables. On one hand, if a name is assigned
anywhere in a function or a method, it's a local variable (unless
there's a global statement, of course.) This analysis is done
at compile time.

On the other hand, the variable does not exist until it's
assigned at run time, so if your assignment is in an if statement
(which yours is) then it's possible that it won't get assigned
before it's used. That's what is happening here.

John Roth






More information about the Python-list mailing list