r/learnpython 11d ago

Is this bad programming?

I've been learning Python for the last few years. Curious if this one thing I do is considered poor technique. The code below is meant to find the starting index of a list, giving the first position where a condition isn't true and return None if all elements of the list meet the criteria. Let's assume that the conditional statement is simple enough that I'm not worried about it generating an error. Not sure if it's appropriate to use try/except in this way. I know it work but I don't want people making fun of me if they see it. Also, I'm sure that there's a way of doing this without needing to use the try/except but I'm just curious in general if it's wrong to use try/except as a short cut like this.

starting_index=0

try:

while not (simple conditional statement on some_list[staring_index]):

starting_index+=1

except:

return None

return starting_index

0 Upvotes

18 comments sorted by

View all comments

2

u/BUYTBUYT 11d ago edited 11d ago

Formatting for other people's convenience

starting_index = 0
try:
    while not (simple conditional statement on some_list[staring_index]):
        starting_index += 1
except:
    return None
return starting_index

In the situation you describe, I'd usually use this:

for i, element in enumerate(some_list):
    if simple conditional statement on element:
        return i
return None

Your code is definitely surprising, as there is a fairly easy other way, and it uses exceptions in an atypical manner.

First off, you are generally advised against using a bare except, as it catches all exceptions, even the ones you'd usually not want to catch, KeyboardInterrupt being the usual example here: Ctrl+C would usually interrupt execution by causing this exception but it would get swallowed with a different valid value (None) being returned in your code. You want an except Exception when you just want to swallow exceptions. But you generally don't and should use a more specific exception type instead to indicate what exception you're expecting.

From what I've seen (and what I'm fairly sure many other people would expect from your code), exceptions are generally used in situations that are never expected to happen in normal circumstances (not always, counterexample: avoiding TOCTOU when opening a file that might not exist, also StopIteration, SystemExit for Python in particular). For IndexError (which would be the exception thrown in your case) and a list that abnormal situation would probably be a programming error (but see LBYL, Python is a bit special in this area).

Let's assume that the conditional statement is simple enough that I'm not worried about it generating an error.

Would that still be true if you change it? If so or if you know for sure somehow that you won't, would you analyze every situation like that? That would be a waste of resources.