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


Groups > comp.lang.python > #99755

Re: Question about code writing '% i, callback'

Newsgroups comp.lang.python
Date 2015-11-30 09:50 -0800
References <25af8ac3-5fc7-44bd-a73f-7a870b69515a@googlegroups.com> <mailman.45.1448905059.14615.python-list@python.org>
Message-ID <06c312b2-a137-46e1-b31c-c9c2224224ad@googlegroups.com> (permalink)
Subject Re: Question about code writing '% i, callback'
From fl <rxjwg98@gmail.com>

Show all headers | View raw


On Monday, November 30, 2015 at 12:37:52 PM UTC-5, Terry Reedy wrote:
> On 11/30/2015 11:44 AM, fl wrote:
> 
> > I come across the following code snippet.
> 
> > for i in range(10):
> >      def callback():
> >          print "clicked button", i
> >      UI.Button("button %s" % i, callback)
> 
> > http://effbot.org/zone/default-values.htm
> 
> Note that the above is an intentional example of common buggy code.  It 
> is followed by a version that works, with 'i=i' added to the callback 
> header.
> 
> -- 
> Terry Jan Reedy

With the following code, there is no bug as the original author said.


class buibutton():
    print 'sd'
    def __nonzero__(self):
       return False
       
    def Button(self, ii, callbackk):
        callbackk()
        return

for i in range(10):
    def callback():
        print "clicked button", i
    UI.Button("button %s" % i, callback)

only to find that all callbacks print the same value (most likely 9, in this case). 

Why does it have no bug?

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


Thread

Question about code writing '% i, callback' fl <rxjwg98@gmail.com> - 2015-11-30 08:44 -0800
  Re: Question about code writing '% i, callback' Zachary Ware <zachary.ware+pylist@gmail.com> - 2015-11-30 10:53 -0600
  Re: Question about code writing '% i, callback' Zachary Ware <zachary.ware+pylist@gmail.com> - 2015-11-30 10:54 -0600
  Re: Question about code writing '% i, callback' Ian Kelly <ian.g.kelly@gmail.com> - 2015-11-30 11:01 -0600
    Re: Question about code writing '% i, callback' fl <rxjwg98@gmail.com> - 2015-11-30 10:55 -0800
      Re: Question about code writing '% i, callback' Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-11-30 20:44 -0500
      Re: Question about code writing '% i, callback' Ian Kelly <ian.g.kelly@gmail.com> - 2015-12-01 09:53 -0600
  Re: Question about code writing '% i, callback' fl <rxjwg98@gmail.com> - 2015-11-30 09:36 -0800
    Re: Question about code writing '% i, callback' Ian Kelly <ian.g.kelly@gmail.com> - 2015-11-30 11:24 -0700
  Re: Question about code writing '% i, callback' Terry Reedy <tjreedy@udel.edu> - 2015-11-30 12:36 -0500
    Re: Question about code writing '% i, callback' fl <rxjwg98@gmail.com> - 2015-11-30 09:50 -0800

csiph-web