On 11/30/2012 11:05 AM, andrea crotti wrote: > Well I knew that this works fine, even if I feel a bit guilty to do > this, and better is: > > foo = 'bar' if some_condition else 'baz' > > Anyway for me the suprise is that something that is defined *later* at > the module scope is found in a function which is defined *earlier*.
It would have been nice if you had indicated in your original post just *what* you considered "shocking" about the code sample. The code was valid, and we all had to guess what about it was puzzling you. Like most others, I first guessed you were confused about the definition being in an if statement. Then I thought you were confused by the with statement, since it's not as obvious that "as" binds the name to the object in the same way as assignment. But I never would have guessed that you were confused about the order of execution in a module. The source code in a module is executed in order, including function definitions defined at top level. However, such a function definition's execution creates a function object, and assigns a global name (usually) to that object. It does not "execute" the object. When that function is executed later, it then looks for global variables for stuff that's not defined within its own scope. So by the time the function references the 'out' name, it's been successfully added to the global namespace. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list