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












2















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?










share|improve this question


















  • 1





    Thanks to the OP for introducing me to python f-strings

    – NotAnAmbiTurner
    Nov 18 '18 at 21:24
















2















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?










share|improve this question


















  • 1





    Thanks to the OP for introducing me to python f-strings

    – NotAnAmbiTurner
    Nov 18 '18 at 21:24














2












2








2


0






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?










share|improve this question














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?







python exception exception-handling






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 16:45









John Humphreys - w00teJohn Humphreys - w00te

19.7k26104196




19.7k26104196








  • 1





    Thanks to the OP for introducing me to python f-strings

    – NotAnAmbiTurner
    Nov 18 '18 at 21:24














  • 1





    Thanks to the OP for introducing me to python f-strings

    – NotAnAmbiTurner
    Nov 18 '18 at 21:24








1




1





Thanks to the OP for introducing me to python f-strings

– NotAnAmbiTurner
Nov 18 '18 at 21:24





Thanks to the OP for introducing me to python f-strings

– NotAnAmbiTurner
Nov 18 '18 at 21:24












2 Answers
2






active

oldest

votes


















1














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.






share|improve this answer































    0














    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.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305044%2fpython-define-variables-before-try-catch-or-just-let-them-bubble-out%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      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.






      share|improve this answer




























        1














        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.






        share|improve this answer


























          1












          1








          1







          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.






          share|improve this answer













          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 18 '18 at 21:34









          NotAnAmbiTurnerNotAnAmbiTurner

          753522




          753522

























              0














              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.






              share|improve this answer






























                0














                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.






                share|improve this answer




























                  0












                  0








                  0







                  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.






                  share|improve this answer















                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 19 '18 at 6:18

























                  answered Nov 18 '18 at 20:59









                  digitalarbeiterdigitalarbeiter

                  1,7001112




                  1,7001112






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305044%2fpython-define-variables-before-try-catch-or-just-let-them-bubble-out%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Bressuire

                      Vorschmack

                      Quarantine