I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Use a global variable
Personally, I do not like the global variables. But, my proposal is based on https://stackoverflow.com/a/19877437/1083704 answer
where user needs to declare a global variable
ranks
, every time you need to call thereport
. My improvement eliminates the need to initialize the function variables from the user.The following solution is inspired by the answer by Elias Zamaria, but contrary to that answer does handle multiple calls of the outer function correctly. The "variable"
inner.y
is local to the current call ofouter
. Only it isn't a variable, since that is forbidden, but an object attribute (the object being the functioninner
itself). This is very ugly (note that the attribute can only be created after theinner
function is defined) but seems effective.There is another way to implement nonlocal variables in Python 2, in case any of the answers here are undesirable for whatever reason:
It is redundant to use the name of the function in the assignment statement of the variable, but it looks simpler and cleaner to me than putting the variable in a dictionary. The value is remembered from one call to another, just like in Chris B.'s answer.
Rather than a dictionary, there's less clutter to a nonlocal class. Modifying @ChrisB's example:
Then
Each outer() call creates a new and distinct class called context (not merely a new instance). So it avoids @Nathaniel's beware about shared context.