Carl Banks wrote: > Say you have a suite of functions, all of which are called by some main > function and each other, and all of which need to access a lot of the > same data. The best, most straightforward way to do it is to have the > common data be a local variable of the main function, and nest the > suite inside it. The other way to do it, passing around a common data > structure, add complexity and hurts performance.
This could use an example. It'll be a little mathematical; bear with me. Say you want to calculate a list of points of an iterated fractal. Here's the idea: you have a set of linear transformations. You take the origin (0,0) as the first point, and then apply each transformation in turn to get a new point. You recursively apply each transformation at each additional point, up to a certain depth. What's the best way to write such a function? Using a nested function, it's easy as pie. (Details may be a little wrong....) . def ifs(transformations, maxdepth): . def add_point(x,y,angle,depth): . ifspoints.append((x,y,angle)) . if depth < maxdepth: . for t in transformations: . nx = x + t.x*cos(angle) - t.y*sin(angle) . ny = y + t.x*sin(angle) * t.y*cos(angle) . nangle = angle + t.angle . add_point(nx,ny,nangle,depth+1) . ifspoints = [] . add_point(0.0, 0.0, 0.0, 0) . return ifspoints If you didn't have the nested function, you'd have to pass not only depth, but also maxdepth, transformations, and ifspoints around. If you had something a little more complex than this, with more than one nested function and more complex pieces of data you'd need to pass around, the savings you get from not having to pass a data structure around and referncing all that data though the structure can be quite a lot. -- CARL BANKS -- http://mail.python.org/mailman/listinfo/python-list