amazing scope?

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Nov 30 06:24:59 EST 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..
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

From what I understand from the with documentation http://docs.python.org/2/reference/compound_stmts.html#with

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.

JM



-- IMPORTANT NOTICE: 

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