help with NameError

Torsten Marek shlomme at gmx.net
Tue May 27 11:35:23 EDT 2003


Shadri Shah schrieb:
> Hello,
> 
> I request help in understanding why I'm getting NameError here in the code below:
> 
> import re
> 
> def t(s):
>     k = []
>     
>     def g(j):
>         global k
>         k.append(j.group(0))
>         return 'p'
>     
>     re.sub('f',g,s)
>     
>     print k
> 
> if __name__ == "__main__":
>     t('abc f xyz f')
> 

"global k" searches a symbol k at global scope, and there isn't any "k"
defined. You access k, just leave out "global k". For further
information, read something about nested scopes, either on the list
(there's plenty about it), or in the python doc.

Torsten






More information about the Python-list mailing list