[Tutor] python closures

Hugo Arts hugo.yoshi at gmail.com
Tue Dec 1 09:36:53 CET 2009


On Tue, Dec 1, 2009 at 8:42 AM, spir <denis.spir at free.fr> wrote:
> Great example, thank you.
>
> By the way, do you know the idiom:
>
> def makeInc(start):
>   def inc():
>      inc.n += 1
>      print inc.n
>   inc.n = start
>   # 'start' may change now
>   # ...
>   return inc
>
> inc= makeInc(start=3)
> inc()
>
> I find it much nicer than a pseudo default value, for it explicitely shows that 'n' is, conceptually speaking, an attribute of the func (read: a closure upvalue). Let's take advantage of the fact python funcs are real objects!

Well, if you need an attribute maintained between calls like that I
think a generator is much nicer to write:

def inc(start):
    while True:
        yield start
        start += 1

>>> i = inc(3)
>>> i.next()
3
>>> i.next()
4

There might be a use-case where function attributes fit better, can't
think of one right now though.

Hugo


More information about the Tutor mailing list