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

Peter Otten __peter__ at web.de
Sun Sep 22 04:15:02 EDT 2013


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's not limited to turtle, Python in general forces you to make shared 
state explicit. 

Simple alternatives to global would be a degenerate class

class state:
    pass

or a magic import

import __main__ as state

With both of these (pseudo-)globals can be set with

state.some_global = some_value

However, most of the names you list above look like their values need not be 
altered from within the function and thus the name not be declared global 
anyway. To be sure you'd have to show us the code...






More information about the Python-list mailing list