Nested function scope problem

enigmadude at rock.com enigmadude at rock.com
Wed Aug 9 15:15:19 EDT 2006


I agree with the previous comments that this approach is "bad form".
But if you absolutely *must* modify an enclosing function's variables
with an inner function, all you need to do is remember that a Python
function is an object too, so it can be assigned attributes. ;-)

def outer():
    outer.x = 1
    print outer.x

    def inner():
        outer.x = 2

    inner()
    print outer.x


Josiah Manson wrote:
> 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')




More information about the Python-list mailing list