Skip to main content

Python: Modifying a Counter in a Closure

I helped a fellow Pythonista with a problem today, and it reminded me that a lot of people might not know about the trick of using a list to box variables within a closure. If that doesn't make sense, read the code below:
def counter(start):

"""Create a counter starting at ``start``."""

# The value "curr" needs to be wrapped in a list. Otherwise, when
# "+=" is used in "inc", Python binds the variable at that scope
# instead of at this scope. We don't want to redefine a variable at
# the inner scope. We want to modify the variable at this outer
# scope. Java programmers would call this "boxing", but they would
# use an Integer instance instead of a list.

curr = [start]

def inc():
"""Increment the counter and return the new value."""
curr[0] += 1
return curr[0]

return inc


if __name__ == '__main__':
c = counter(5)
for i in range(3):
print c() # Prints 6 7 8.

Comments

PJE said…
There's a better way, from a readability point of view. Replace "curr = [start]" with "inc.count = start", and move it after the "def inc():" block. Now replace all uses of "curr[0]" with "inc.count".

Now your code will be understandable even to the uninitiated. :)
jjinux said…
Nice :)
dan said…
I've been using that array idiom for a while now but it always seemed a bit icky to me. Never thought of using a function attribute to do the job - it looks a lot nicer.
Anonymous said…
def inc(count=[0]):
count[0] += 1
return count[0]
Dirkjan Ochtman said…
I'm kind of surprised that PJE's trick works... How is it that there's a variable "inc" bound to the function within the function itself? Apparently, that would be always the case, but I don't see how that makes sense. It's impossible to declare something in its OWN scope, right?
Anonymous said…
I don't get it. What makes this superior to:

def counter(start, stop):
while start < stop:
yield start
start += 1

for i in counter(5,10):
print i

# prints 5 6 7 8 9

or even

for i in [i + 5 for i in range(3)]:
print i
# prints 5 6 7

?
Anonymous said…
"How is it that there's a variable "inc" bound to the function within the function itself?"

"inc.count" is an attribute on the function object, not a variable inside the function.
Alex said…
You can use this trick to translate the established technique for making private data in Javascript into Python.

class Foo:
  def __init__(self):
     private_vars = [ 0, "Alex" ]

     def count(): return private_vars[0]
     self.count = count

     def set_count(c): private_vars[0] = c
     self.set_count = set_count

     def name(): return private_vars[1]
     self.name = name

     def set_name(n): private_vars[1] = n
     self.set_name = set_name

Now you can do this:

f = Foo()
f.set_name("someone else...")
jjinux said…
> def inc(count=[0]):
> count[0] += 1
> return count[0]

Unfortunately, this provides only a single global counter, which is insufficient. The other versions create a new counter for each closure.

Mutable static defaults--ugly ;)
jjinux said…
> I'm kind of surprised that PJE's trick works...

Functions are objects. With the exception of some immutable objects like strings, you can attach stuff to any object.
jjinux said…
> I don't get it. What makes this superior to:

Sorry, you missed my point. You are absolutely right that generators are better mechanisms to create counters. I wasn't really trying to create a counter. I was trying to show how to modify a lexically scoped, non-local variable using the list trick.
jjinux said…
> You can use this trick to translate the established technique for making private data in Javascript into Python.

Nice! I hadn't seen that :)
Anonymous said…
> Functions are objects. With the exception of some immutable objects like strings, you can attach stuff to any object.

I understand that I can attach attributes to any function. What I don't understand is that the function object is available in the function body when the function evaluation hasn't been completed yet (in the function body).
jjinux said…
> I understand that I can attach attributes to any function. What I don't understand is that the function object is available in the function body when the function evaluation hasn't been completed yet (in the function body).

Oh, now I see your confusion. You are correct that you cannot attach function attributes (that I know of) before the function definition is done. PJE was saying you can attach attributes to the inner function from the outer function.
Anonymous said…
But that is EXACTLY what he's saying: "replace all uses of 'curr[0]' with 'inc.count'. The uses of curr[0] are all *inside* inc(). And it works, too, I tested it in the interactive interpreter:

>>> def inc():
... inc.count += 1
... return inc.count
...
>>> inc.count = 0
>>> inc()
1
>>> inc()
2

Hmm, that makes sense, actually. By the time the function body is executed, the inc() function is fully defined in the global namespace, so now the function body can access the link to the function object in the global scope.
jjinux said…
> Hmm, that makes sense, actually.

Ah, yes, you are correct. Very good. It's not really "global" of course, but I think you've nailed it.

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

ERNOS: Erlang Networked Operating System

I've been reading Dreaming in Code lately, and I really like it. If you're not a dreamer, you may safely skip the rest of this post ;) In Chapter 10, "Engineers and Artists", Alan Kay, John Backus, and Jaron Lanier really got me thinking. I've also been thinking a lot about Minix 3 , Erlang , and the original Lisp machine . The ideas are beginning to synthesize into something cohesive--more than just the sum of their parts. Now, I'm sure that many of these ideas have already been envisioned within Tunes.org , LLVM , Microsoft's Singularity project, or in some other place that I haven't managed to discover or fully read, but I'm going to blog them anyway. Rather than wax philosophical, let me just dump out some ideas: Start with Minix 3. It's a new microkernel, and it's meant for real use, unlike the original Minix. "This new OS is extremely small, with the part that runs in kernel mode under 4000 lines of executable code.&quo

Haskell or Erlang?

I've coded in both Erlang and Haskell. Erlang is practical, efficient, and useful. It's got a wonderful niche in the distributed world, and it has some real success stories such as CouchDB and jabber.org. Haskell is elegant and beautiful. It's been successful in various programming language competitions. I have some experience in both, but I'm thinking it's time to really commit to learning one of them on a professional level. They both have good books out now, and it's probably time I read one of those books cover to cover. My question is which? Back in 2000, Perl had established a real niche for systems administration, CGI, and text processing. The syntax wasn't exactly beautiful (unless you're into that sort of thing), but it was popular and mature. Python hadn't really become popular, nor did it really have a strong niche (at least as far as I could see). I went with Python because of its elegance, but since then, I've coded both p