Mike wrote: > I think the answer is that 'def' is an executable statement in python > rather than a definition that the compiler interprets at compile time. > > As a result the compiler can evaluate 'foo()' when it defines 'bar', so > it does. > > The following works as expected: > def bar(): > print foo() > > Hopefully somebody more knowledgable will also respond >
The def statement is, as you say, an executable statement. It creates a new function object, so it is quite useful to look directly at the function type to see what arguments its constructor takes: >>> import types >>> help(types.FunctionType) Help on class function in module __builtin__: class function(object) | function(code, globals[, name[, argdefs[, closure]]]) | | Create a function object from a code object and a dictionary. | The optional name string overrides the name from the code object. | The optional argdefs tuple specifies the default argument values. | The optional closure tuple supplies the bindings for free variables. ... The arguments passed to the constructor when the def statement is executed are: a code object. This object is created once when the module containing the function is compiled. The def doesn't have to do anything with the actual code, so it will take the same time whether you def a function of 1 line or 1000 lines. globals is the same value as you get by calling the builtin globals(). name is the function name. It's a string constant. argdefs is the interesting one here. It is a tuple of the default argument values and is created every time the def statement is executed. closure is another tuple which is created every time the def statement is executed. This allows a def nested inside another function to reference the current local variables which are in scope when the def executes. This tuple can only contain cell objects which are an internal object type used for scoped variables. So, argdefs and closure are the two things which are different each time you def a function, everything else is constant and shared between definitions of the same function. -- http://mail.python.org/mailman/listinfo/python-list