Why do I have to use "global" so much when using Turtle?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Sep 22 06:43:20 EDT 2013


On Sat, 21 Sep 2013 21:39:07 -0700, John Ladasky wrote:

> Hi, folks,
> 
> Some of you may remember that I am teaching some high school students
> how to program.  Because they all love graphics, I have been
> investigating the turtle module, which I gather is built on top of Tk. 
> I can see that real-time applications are possible.  I'm writing a
> classic "bouncing-balls" program to demonstrate to my students.
> 
> In the main program code, I instantiate a turtle.Screen, named sc.
> 
> I draw a bounding box, whose size is described by the variables edgew
> and edgeh.  I have a list of Turtle objects, which I named balls.  I
> have a timer interval stored in tick.
> 
> In the main loop of my program, I bind a function to update the
> positions of the balls to a timer, thus:
> 
> sc.ontimer(move_balls, tick)
> 
> Inside my move_balls function, I could not get ANYTHING done without the
> following declaration:
> 
> global balls, edgew, edgeh, tick

That doesn't sound right. You don't need to declare globals unless you 
are rebinding them (assigning to the name). So if you do something like 
this:

def move_balls():
    for ball in balls:
        do_something_with(ball)


you're not assigning to global "balls" so no global declaration is 
needed. But if you do this:


def move_balls():
    balls = sorted(balls)  # say
    for ball in balls:
        do_something_with(ball)


then you need a global declaration since you're assigning to the global 
variable. Likewise for tick, edgew and edgeh -- if you're just *reading* 
their value, you don't need to declare them.


> For a while, I had a "quit" function that I bound to the q key:
> 
> sc.onkeypress(quit, "q")
> 
> The quit function simply printed a message, and then called sc.bye(). 
> As with move_balls, quit wouldn't work unless I had a "global sc"
> declaration in it.

Again, that sounds wrong. This should work, since sc is not assigned to:

def quit():
    print("Bye now!")
    sc.bye()


If that's not the case, there's something you're not telling us about 
your code. Actual working examples are appreciated.




-- 
Steven



More information about the Python-list mailing list