Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52655

Re: Local variable in a closure

From Dave Angel <davea@davea.name>
Subject Re: Local variable in a closure
Date 2013-08-18 10:44 +0000
References <107941d9-a981-4dd6-8460-336afc16f025@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.26.1376822665.23369.python-list@python.org> (permalink)

Show all headers | View raw


w.w.milner@googlemail.com wrote:

> Is f local or not?
> http://pastebin.com/AKDJrbDs

Please have a little respect, and include the source in your message. 
You managed quite nicely to keep it small, but you put it in an obscure
place that some people won't be able to reach, and that might not
survive for the archives.

def multiplier(f):
    def times(n):
        # is f local?
        nonlocal f
        f=f+1
        # if not, why is it here?
        print("Locals: ",locals())
        return n*f   
    return times

times2 = multiplier(2)
print(times2(4)) # 3X4=12
print(times2(4)) # 4X4=16

Inside function times, the variable 'f' is a free variable, not a local.
 You can prove that to yourself by adding a dis.dis(times) just before
the "return times" statement.  Here's how it begins:

  7           0 LOAD_DEREF               0 (f) 
              3 LOAD_CONST               1 (1) 
              6 BINARY_ADD           
              7 STORE_DEREF              0 (f) 


In the dis.dis listing, the LOAD_DEREF and STORE_DEREF opcodes are
referring to free variables, the LOAD_FAST is referring to a local, and
the LOAD_GLOBAL is referring to a global.

The locals() function is just over-simplifying.  it's only a convenience
function, not what I would consider part of the language, and it wasn't
apparently deemed necessary to have a separate function for debugging
free varaibles.

-- 
DaveA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Local variable in a closure w.w.milner@googlemail.com - 2013-08-18 02:41 -0700
  Re: Local variable in a closure Chris Angelico <rosuav@gmail.com> - 2013-08-18 11:28 +0100
  Re: Local variable in a closure Ian Kelly <ian.g.kelly@gmail.com> - 2013-08-18 04:40 -0600
  Re: Local variable in a closure Dave Angel <davea@davea.name> - 2013-08-18 10:44 +0000
  Re: Local variable in a closure Terry Reedy <tjreedy@udel.edu> - 2013-08-18 16:42 -0400

csiph-web