global variables and local functions.

Inyeol Lee inyeol_lee at yahoo.com
Thu Aug 29 20:12:04 EDT 2002


'global' keyword is not required when appending something to a global list
in local scope, since there's no assignment with list.append(). For example,

>>> L = []
>>> def f(): L.append(1)
>>> f()
>>> L
[1]

However, if you use '+=' things are changing.

>>> def g(): L += [1]
>>> g()
UnboundLocalError: local variable 'L' referenced before assignment

- Inyeol Lee



Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote in message news:<akll4h$d88$1 at slb0.atl.mindspring.net>...
> Micah Mayo fed this fish to the penguins on Wednesday 28 August 2002 
> 09:11 pm:
> 
> >
> > okay,
> > 
> > sourcePath = []
> > destPath = []
> > mlistLen = 0
> > 
> > populateLists():
> 
>         I'm stale, and tend not to use globals if I can avoid them but...
> 
>         Try inserting:
> 
>         global mlistLen
>         global sourcePath
>         global destPath
> 
> at this location. I'm presuming your complaint is that mlistLen et al 
> aren't updating.
> 
> >       textFile = open('movelist')
> >       for eachLine in textFile.readlines():
> >               source, dest = eachLine.split()
> >               sourcePath.append(source)
> >               destPath.append(dest)
> >               mlistLen += 1
> > 
> > moveFiles():
> 
>         Also insert the global statements (syntax may allow comma separated 
> list -- check the docs)
> 
>         Alternatively, forget about mlistLen totally and use 
> 
>         for x in range(len(sourcePath))
> >       for x in range(mlistLen):
> >               shutil.copy2(sourcePath[x],destPath[x])
> >               
> > So, that's the part that doesn't work almost line for line.
>  --
>  > ============================================================== <
>  >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
>  >      wulfraed at dm.net     |       Bestiaria Support Staff       <
>  > ============================================================== <
>  >        Bestiaria Home Page: http://www.beastie.dm.net/         <
>  >            Home Page: http://www.dm.net/~wulfraed/             <



More information about the Python-list mailing list