#1 Crossbones+ - Reputation: 1329
Posted 15 February 2012 - 07:58 PM
[source lang="python"]def count_if( func, seq): count = [0] def count_func( x ): if ( func(x) ): count[0] += 1 for x in seq: count_func(x) return count[0][/source]
why do I have to make count a one element list? (obviously I could implement this without a closure I'm just trying to understand how they work.)
#3 Crossbones+ - Reputation: 1329
Posted 15 February 2012 - 08:10 PM
[source lang="python"]def count_if( func, seq): count = 0 def count_func( x ): if ( func(x) ): count += 1 for x in seq: count_func(x) return count[/source]
yields the error "UnboundLocalError: local variable 'count' referenced before assignment." When I google that I see people talking about this sort of thing but I haven't seen a clear explanation.
#4 Members - Reputation: 952
Posted 15 February 2012 - 08:51 PM
#5 Crossbones+ - Reputation: 1329
Posted 15 February 2012 - 09:08 PM
But then why does the list version work? ... Oh, I guess I see, because count[0] += 1 does not tell python to create a one element list if count doesn't exist; if count doesn't exist count[0] += 1 is an error. if a list version of count exists *only* in an enclosing scope and you attempt this assignment python assumes you mean that one?I barely know Python, but this StackOverflow thread seems to describe the problem well enough to me. Basically: if you assign to a variable, that variable is created in the local scope, even if there is an identifier with the same name visible from an enclosing scope. Consequently, if you just read from a captured variable, things are dandy. But if you perform an assignment, even after the read, then it will assume that all references in that (enclosed) scope refer to a closure local. Apparently this is remedied (not very nicely, it has to be said) in Python 3.x.
#6 Members - Reputation: 952
Posted 15 February 2012 - 09:24 PM






