views:

25

answers:

1

I've just written a utility in Python to do something I need (irrelevant, but it's to generate a ctags-compatible tag file for an in-house DSL).

Anyway- I'm opening and reading the file in the context of a with statement, and I'm curious, how do people tend to handle failures in that process?

My solution is

with open(filename, 'rt') as f:
    content = f.read()

matches = re.findall(REGEX, content)

if len(matches) > 0:
    # do more stuff...
    pass

I put the match check outside of the with statement because I like having the file closed and done with. However, if content never gets built, this will fail.

My solution was to initialize content to the empty string just above this bit of code, but the feeling I get is that I'd like the function just to end; an exception gets thrown out of the function or something.

In this case, I could put the rest of the function into the with block but that broadens the scope of the open file. I can create content before the with block so that it exists in light of a failure. I'm curious, however, what other solutions do people like to see (assuming the question makes any sense in the first place)?

I suppose I'd sorta like something like this:

with open(filename, 'rt') as f:
    content = f.read()
else:
    content = ''

matches = re.findall(REGEX, content)

I will accept the idea that I just need to deal with it and leave the file open for the rest of the function if that's the general consensus. :)

+1  A: 

What I would do is as you said:

content = ''
with open(filename, 'rt') as f:
    content = f.read()

matches = re.findall(REGEX, content)

as the cost for regexing and checking matches would be negligable for an empty string.

However, closing the file immediately isn't that important as long as it is closed in the end, assuming that you don't reuse it.

Muhammad Alkarouri