amazing scope?

Jean-Michel Pichavant jeanmichel at
Fri Nov 30 12:24:59 CET 2012

----- Original Message -----
> I wrote a script, refactored it and then introducing a bug as below:
> def record_things():
>     out.write("Hello world")
> if __name__ == '__main__':
>     with open('output', 'w') as out:
>         record_things()
> but the shocking thing is that it didn't actually stopped working, it
> still works perfectly!
> 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..
> --

From what I understand from the with documentation

The with block has nothing to do with scopes. It does not define the target within that block, well, actually it does but it defines it for the current scope.
The with block only identifies where to call __enter__ and __exit__.

So I would say that "with open('output', 'w') as out" assignes "out" at the module level.

You may have been mislead by some other languages where a with block purpose is to limit the scope of a variable.



The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.

More information about the Python-list mailing list