John Humphreys
John Humphreys

Reputation: 39294

Python - Define variables before try/catch or just let them bubble out?

Coming from Java and C based languages, this looks odd in Python. The x variable is defined in the try block but used outside of it.

I understand that python does not scope the try block though.

try:
    x = 5
except Exception as e:
    print(str(e))

print(f"x = {x}")

Is this considered to be good form in Python, or is it preferred to set, say, x = None beforehand? or some third option? Why?

Upvotes: 2

Views: 334

Answers (2)

digitalarbeiter
digitalarbeiter

Reputation: 2335

In situations like these, if there is a common execution path after the exception, I usually do something like this (which has a certain if/else-ish touch to it as far as assignment to the variable is concerned):

try:
    price = get_min_price(product)
except Exception as ex:
    print("could not get price for product {}: {}".format(product, ex))
    price = 1000000.0
print(f"price = {price}")
if price <= min_price:
    send_price_alert(user, product, price)

However, more often than not, I structure my code in a way that whatever variables are filled in the try block, I won't be using after the except block:

try:
    price = get_min_price(product)
    print(f"price = {price}")
    if price <= min_price:
        send_price_alert(user, product, price)
except Exception as ex:
    print("could not get price for product {}: {}".format(product, ex))

Here, price isn't used after the except keyword, thus obviating the need for initialization.

Upvotes: 0

NotAnAmbiTurner
NotAnAmbiTurner

Reputation: 2743

There are very few situations where a try: / except: is really the appropriate thing to do. Obviously the example you gave was abstracted, but in my opinion the answer is a hard "no," it's not good form to reference a potentially undeclared variable - if for some reason an error is encountered in the try: before x = 5, then you are going to get an error when you try to print(f"x = {x}").

More to the point, why oh why would the variable be assigned in the try block? I would say a good rule of thumb is to only include in try that portion of the code you are actually testing for exceptions.

Side-notes:

  • I have been previously advised on SO that it's bad form to use a except Exception, because what you really should be doing is handling a certain type of error, or better yet a particular error (eg. except IndexError, which will result in all other types of errors being unhandled)... try / except is something that can easily introduce difficult to diagnose bugs if it's used non-specifically.
  • I'm pretty sure except: and except Exception are equivalent.

Upvotes: 1

Related Questions