Should I test if
something is valid or just try
to do it and catch the exception?
- Is there any solid documentation saying that one way is preferred?
- Is one way more pythonic?
For example, should I:
if len(my_list) >= 4:
x = my_list[3]
else:
x = 'NO_ABC'
Or:
try:
x = my_list[3]
except IndexError:
x = 'NO_ABC'
Some thoughts...
PEP 20 says:
Errors should never pass silently.
Unless explicitly silenced.
Should using a try
instead of an if
be interpreted as an error passing silently? And if so, are you explicitly silencing it by using it in this way, therefore making it OK?
I'm not referring to situations where you can only do things 1 way; for example:
try:
import foo
except ImportError:
import baz
if index in mylist
tests wether index is an element of mylist, not a possible index. You would wantif index < len(mylist)
instead. – Dermatitis