amazing scope?

Ulrich Eckhardt ulrich.eckhardt at
Fri Nov 30 12:23:10 CET 2012

Am 30.11.2012 12:11, schrieb andrea crotti:
> I wrote a script, refactored it and then introducing a bug as below:
> def record_things():
>      out.write("Hello world")

This is a function. Since "out" is not a local variable, it is looked up 
in the surrounding namespace at the time the function is called.

> if __name__ == '__main__':
>      with open('output', 'w') as out:
>          record_things()

This is not in a function, so binding variables affects the containing 
namespace. This includes binding the context manager to "out". Note that 
you could have moved the whole code into a function (e.g. one called 
main()) and then you would have gotten the expected failure.

> What my explanation might be is that the "out" is declared at module
> level somehow, but that's not really intuitive and looks wrong, and
> works both on Python 2.7 and 3.2..

Other than in C/C++/Java and others, indention doesn't introduce a new 
scope, but I understand your intuition. Even simpler, this is how my 
early Python code looked like, in the absence of the C ternary operator 
and the distinction between a variable declaration and an assignment:

  foo = None
  if some_condition:
      foo = 'bar'
      foo = 'baz'

More idiomatic would have been this:

  if some_condition:
      foo = 'bar'
      foo = 'baz'

Summary: I'd say that everything is fine. ;)


More information about the Python-list mailing list