Will McGugan a écrit :
gabor said:
hi,
there are 2 versions of a simple code.
which is preferred?
===
if len(line) >= (n+1):
text = line[n]
else:
text = 'nothing'
===
===
try:
text = line[n]
except IndexError:
text = 'nothing'
===
which is the one you would use?
I would actualy use the following for this particular case..
text = line[n:n+1] or 'nothing'
.... and you would get either a list of one element or a string ...
I think you wanted to write :
text = (line[n:n+1] or ['nothing'])[0]
However, I wouldn't use that because it is hard to read ... you have to
know Python in great detail to know that:
1 - is the expressions "line[i:j]", i and j are replaced with
"len(line)" if they are greater than "len(line)"
2 - so if n > len(line), then line[n:n+1]" == len[len(line):len(line)]
== []
(it is not evident that line[n:n+1] can give an empty list ...)
3 - empty list evaluate to "False"
4 - the "or" operator returns the first argument evaluating to "true"
So, in the end, you use 3 side-effects of Python in the same small
expression ... (1, 2 and 4)
But in general I think it is best to use exceptions like that only where
you expect the code to _not_ throw the exception the majority of times.
Otherwise the simple condition is better. Although I expect there is not
much difference either way..
Will McGugan
What I would do is the following:
- if this happen in a loop, I would, if possible, remove any test and
catch the exception outside the loop !
- otherwise, I would go for the test, as it is more straitforward to read.
Pierre