[Python-ideas] Before and after the colon in funciton defs.

Nick Coghlan ncoghlan at gmail.com
Fri Sep 23 03:31:38 CEST 2011


On Fri, Sep 23, 2011 at 11:11 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 4. Function scoped variables
>
> This is the approach most analogous to C's static variables - named
> variables that are shared across all invocations of a function, rather
> than being local to the current invocation. In essence, each function
> becomes its own closure - just as a function can share state across
> invocations by using an outer function for storage, this technique
> would allow a function to use its *own* cell array for such storage.

Applying this 'functions as their own closure' concept to the classic
counter problem:

    def counter():
        x = 0
        def increment():
            nonlocal x
            x += 1
            return x
        return increment

would become:

    def counter():
        def increment():
            nonlocal x=0
            x += 1
            return x
        return increment

Or, if you wanted a process-global counter:

    def global_counter():
        nonlocal x=0
        x += 1
        return x

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list