"Try:" which only encompasses head of compound statement

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Aug 29 02:58:27 CEST 2007

Jameson.Quinn at gmail.com writes:

> In real life, I want to set some return values to sensible defaults
> if the file doesn't exist, but I want the errors from inside the
> block to trickle up as normal.

Sure. Just be careful only to catch the exceptions that you do want to
handle at that level of the code, and the others will propagate

> And yes, I can easily use a temporary variable for the open file,
> but it really seems to me that this defeats the purpose of the
> 'with' statement - if this were something more dangerous than a
> file, I'd feel mighty leery of having it in a temporary variable
> outside a 'with' for even a moment.

You seem to be confused about one or both of "variables" (which Python
doesn't really have) and the 'with' statement.

When you write::

    input_file = open("foo.txt")
    with input_file:
        # do stuff

there's no "temporary variable". You've merely bound the name
'input_file' to the file object; it's the same file object as is then
used in the 'with' statement. You could bind a dozen other names to
the object and it would still be the same file object.

So, when the 'with' block exits, the context manager will close the
file object, no matter how many names you bind to it.

> So, the options are:
> -temporary variable - could this EVER be more dangerous than the with
> statement (KeyboardInterrupt which is later caught and handled?)

Since it's not a "temporary variable" but rather just a way to refer
to the file object, I don't see the issue you're describing. However
you refer to it, that one file object will be closed when the 'with'
block exits.

> -'tunnel' internal exceptions past the try by wrapping them in a
> TunnelException and then unwrapping them with a containing try block.
> The second looks like a hack to me

Yes, it is. Catch the exceptions you want to handle, let the rest
propagate normally. The context manager created by the 'with'
statement will handle closing the file *and* propagate the exception


> and the first still feels dangerous.

If it's still that way, perhaps you could be more explicit about what
danger you think exists?

 \     "Are you pondering what I'm pondering?" "I think so, Brain, but |
  `\    pants with horizontal stripes make me look chubby."  -- _Pinky |
_o__)                                                   and The Brain_ |
Ben Finney

More information about the Python-list mailing list