J
Josiah Manson
I found that I was repeating the same couple of lines over and over in
a function and decided to split those lines into a nested function
after copying one too many minor changes all over. The only problem is
that my little helper function doesn't work! It claims that a variable
doesn't exist. If I move the variable declaration, it finds the
variable, but can't change it. Declaring the variable global in the
nested function doesn't work either.
But, changing the variable in the containing scope is the whole purpose
of this helper function.
I'm new to python, so there is probably some solution I haven't
encountered yet. Could you please suggest a nice clean solution? The
offending code is below. Thanks.
def breakLine(s):
"""Break a string into a list of words and symbols.
"""
def addTok():
if len(tok) > 0:
ls.append(tok)
tok = ''
ls = []
tok = ''
splitters = '?()&|:~,'
whitespace = ' \t\n\r'
for c in s:
if c in splitters:
addTok()
ls.append(c)
elif c in whitespace:
addTok()
else:
tok = tok + c
addTok()
return ls
#some tests to make sure it works
print breakLine('carolina(Prada):cat(X,Y)')
print breakLine('trouble :bird (X ) &cat ( Y )')
print breakLine('?trouble')
a function and decided to split those lines into a nested function
after copying one too many minor changes all over. The only problem is
that my little helper function doesn't work! It claims that a variable
doesn't exist. If I move the variable declaration, it finds the
variable, but can't change it. Declaring the variable global in the
nested function doesn't work either.
But, changing the variable in the containing scope is the whole purpose
of this helper function.
I'm new to python, so there is probably some solution I haven't
encountered yet. Could you please suggest a nice clean solution? The
offending code is below. Thanks.
def breakLine(s):
"""Break a string into a list of words and symbols.
"""
def addTok():
if len(tok) > 0:
ls.append(tok)
tok = ''
ls = []
tok = ''
splitters = '?()&|:~,'
whitespace = ' \t\n\r'
for c in s:
if c in splitters:
addTok()
ls.append(c)
elif c in whitespace:
addTok()
else:
tok = tok + c
addTok()
return ls
#some tests to make sure it works
print breakLine('carolina(Prada):cat(X,Y)')
print breakLine('trouble :bird (X ) &cat ( Y )')
print breakLine('?trouble')