Python try: ing not to repeat code. try: except and else












1















I have this:



try:    
if session.var:
otherVar = session.var
else:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank
except AttributeError:
util = db.utility[1]
otherVar = session.var = util.freshOutTheBank

...do stuff with otherVar


The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.



How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?










share|improve this question





























    1















    I have this:



    try:    
    if session.var:
    otherVar = session.var
    else:
    util = db.utility[1]
    otherVar = session.var = util.freshOutTheBank
    except AttributeError:
    util = db.utility[1]
    otherVar = session.var = util.freshOutTheBank

    ...do stuff with otherVar


    The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.



    How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?










    share|improve this question



























      1












      1








      1








      I have this:



      try:    
      if session.var:
      otherVar = session.var
      else:
      util = db.utility[1]
      otherVar = session.var = util.freshOutTheBank
      except AttributeError:
      util = db.utility[1]
      otherVar = session.var = util.freshOutTheBank

      ...do stuff with otherVar


      The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.



      How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?










      share|improve this question
















      I have this:



      try:    
      if session.var:
      otherVar = session.var
      else:
      util = db.utility[1]
      otherVar = session.var = util.freshOutTheBank
      except AttributeError:
      util = db.utility[1]
      otherVar = session.var = util.freshOutTheBank

      ...do stuff with otherVar


      The case is that the session.var might not exist or could be None. This code is also run more than once by a user during a session.



      How do I avoid repeating the code. I basically want to do an 'except and else' or am I looking at this incorrectly?







      python python-2.7 web2py try-except






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 17 '18 at 0:20









      Blckknght

      62.4k556100




      62.4k556100










      asked Nov 17 '18 at 0:00









      EddieEddie

      174




      174
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Assuming this is a web2py session object, note that it is an instance of gluon.Storage, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None rather than raising an exception. So, you can simply do something like:



          otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank


          Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None, you cannot use hasattr(session, 'var'), as that will return True even if there is no 'var' key. Instead, you can check session.has_key('var'), which will return False if there is no 'var' key.






          share|improve this answer
























          • I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

            – Eddie
            Nov 18 '18 at 11:54



















          1














          You can avoid using session.var if it doesn't exist by checking for it first, using hasattr. This avoids the need for the try/except block all together.



          if hasattr(session, 'var') and session.var is not None:
          ...
          else:
          ...


          An alternative might be to have the else in your original code just raise an exception to get to the except block, but it's sort of ugly:



          try:
          if session.var:
          ...
          else:
          raise AttributeError
          except AttributeError:
          ...


          In this situation, I think the "Look Before you Leap" style of programming (using hasattr) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.



          If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var function, it could return from the successful case (inside the try and if blocks), and the two error cases could be resolved later:



          def get_session_var(session):
          try:
          if session.var:
          return session.var
          except AttributeError:
          pass

          util = db.utility[1]
          session.var = util.freshOutTheBank
          return session.var





          share|improve this answer
























          • Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

            – user2357112
            Nov 17 '18 at 0:23











          • As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

            – Anthony
            Nov 17 '18 at 14:24











          • I was trying to avoid checking. Going with the Duck-Typing concept.

            – Eddie
            Nov 18 '18 at 11:52











          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%2f53346918%2fpython-try-ing-not-to-repeat-code-try-except-and-else%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














          Assuming this is a web2py session object, note that it is an instance of gluon.Storage, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None rather than raising an exception. So, you can simply do something like:



          otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank


          Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None, you cannot use hasattr(session, 'var'), as that will return True even if there is no 'var' key. Instead, you can check session.has_key('var'), which will return False if there is no 'var' key.






          share|improve this answer
























          • I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

            – Eddie
            Nov 18 '18 at 11:54
















          1














          Assuming this is a web2py session object, note that it is an instance of gluon.Storage, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None rather than raising an exception. So, you can simply do something like:



          otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank


          Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None, you cannot use hasattr(session, 'var'), as that will return True even if there is no 'var' key. Instead, you can check session.has_key('var'), which will return False if there is no 'var' key.






          share|improve this answer
























          • I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

            – Eddie
            Nov 18 '18 at 11:54














          1












          1








          1







          Assuming this is a web2py session object, note that it is an instance of gluon.Storage, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None rather than raising an exception. So, you can simply do something like:



          otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank


          Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None, you cannot use hasattr(session, 'var'), as that will return True even if there is no 'var' key. Instead, you can check session.has_key('var'), which will return False if there is no 'var' key.






          share|improve this answer













          Assuming this is a web2py session object, note that it is an instance of gluon.Storage, which is like a dictionary with two exceptions: (1) keys can be accessed like properties, and (2) accessing a non-existent key/property returns None rather than raising an exception. So, you can simply do something like:



          otherVar = session.var = session.var if session.var else db.utility[1].freshOutTheBank


          Note, if you want to distinguish between non-existent keys and keys that have an explicit value of None, you cannot use hasattr(session, 'var'), as that will return True even if there is no 'var' key. Instead, you can check session.has_key('var'), which will return False if there is no 'var' key.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 17 '18 at 14:22









          AnthonyAnthony

          23.9k32051




          23.9k32051













          • I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

            – Eddie
            Nov 18 '18 at 11:54



















          • I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

            – Eddie
            Nov 18 '18 at 11:54

















          I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

          – Eddie
          Nov 18 '18 at 11:54





          I am so sure I ended up in this position because there was an AttributeError being thrown and I was trying to deal with it. However, I have changed the code to a simply if-else and it's working even on login when the variable hasn't been set. Thanks.

          – Eddie
          Nov 18 '18 at 11:54













          1














          You can avoid using session.var if it doesn't exist by checking for it first, using hasattr. This avoids the need for the try/except block all together.



          if hasattr(session, 'var') and session.var is not None:
          ...
          else:
          ...


          An alternative might be to have the else in your original code just raise an exception to get to the except block, but it's sort of ugly:



          try:
          if session.var:
          ...
          else:
          raise AttributeError
          except AttributeError:
          ...


          In this situation, I think the "Look Before you Leap" style of programming (using hasattr) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.



          If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var function, it could return from the successful case (inside the try and if blocks), and the two error cases could be resolved later:



          def get_session_var(session):
          try:
          if session.var:
          return session.var
          except AttributeError:
          pass

          util = db.utility[1]
          session.var = util.freshOutTheBank
          return session.var





          share|improve this answer
























          • Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

            – user2357112
            Nov 17 '18 at 0:23











          • As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

            – Anthony
            Nov 17 '18 at 14:24











          • I was trying to avoid checking. Going with the Duck-Typing concept.

            – Eddie
            Nov 18 '18 at 11:52
















          1














          You can avoid using session.var if it doesn't exist by checking for it first, using hasattr. This avoids the need for the try/except block all together.



          if hasattr(session, 'var') and session.var is not None:
          ...
          else:
          ...


          An alternative might be to have the else in your original code just raise an exception to get to the except block, but it's sort of ugly:



          try:
          if session.var:
          ...
          else:
          raise AttributeError
          except AttributeError:
          ...


          In this situation, I think the "Look Before you Leap" style of programming (using hasattr) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.



          If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var function, it could return from the successful case (inside the try and if blocks), and the two error cases could be resolved later:



          def get_session_var(session):
          try:
          if session.var:
          return session.var
          except AttributeError:
          pass

          util = db.utility[1]
          session.var = util.freshOutTheBank
          return session.var





          share|improve this answer
























          • Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

            – user2357112
            Nov 17 '18 at 0:23











          • As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

            – Anthony
            Nov 17 '18 at 14:24











          • I was trying to avoid checking. Going with the Duck-Typing concept.

            – Eddie
            Nov 18 '18 at 11:52














          1












          1








          1







          You can avoid using session.var if it doesn't exist by checking for it first, using hasattr. This avoids the need for the try/except block all together.



          if hasattr(session, 'var') and session.var is not None:
          ...
          else:
          ...


          An alternative might be to have the else in your original code just raise an exception to get to the except block, but it's sort of ugly:



          try:
          if session.var:
          ...
          else:
          raise AttributeError
          except AttributeError:
          ...


          In this situation, I think the "Look Before you Leap" style of programming (using hasattr) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.



          If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var function, it could return from the successful case (inside the try and if blocks), and the two error cases could be resolved later:



          def get_session_var(session):
          try:
          if session.var:
          return session.var
          except AttributeError:
          pass

          util = db.utility[1]
          session.var = util.freshOutTheBank
          return session.var





          share|improve this answer













          You can avoid using session.var if it doesn't exist by checking for it first, using hasattr. This avoids the need for the try/except block all together.



          if hasattr(session, 'var') and session.var is not None:
          ...
          else:
          ...


          An alternative might be to have the else in your original code just raise an exception to get to the except block, but it's sort of ugly:



          try:
          if session.var:
          ...
          else:
          raise AttributeError
          except AttributeError:
          ...


          In this situation, I think the "Look Before you Leap" style of programming (using hasattr) is nicer than the usually more Pythonic style of "Easier to Ask Forgiveness than Permission" (which uses exceptions as part of flow control). But either one can work.



          If your code was compartmentalized into smaller functions, it might be even easier to deal with the issue. For instance, if you wrote a get_session_var function, it could return from the successful case (inside the try and if blocks), and the two error cases could be resolved later:



          def get_session_var(session):
          try:
          if session.var:
          return session.var
          except AttributeError:
          pass

          util = db.utility[1]
          session.var = util.freshOutTheBank
          return session.var






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 17 '18 at 0:20









          BlckknghtBlckknght

          62.4k556100




          62.4k556100













          • Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

            – user2357112
            Nov 17 '18 at 0:23











          • As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

            – Anthony
            Nov 17 '18 at 14:24











          • I was trying to avoid checking. Going with the Duck-Typing concept.

            – Eddie
            Nov 18 '18 at 11:52



















          • Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

            – user2357112
            Nov 17 '18 at 0:23











          • As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

            – Anthony
            Nov 17 '18 at 14:24











          • I was trying to avoid checking. Going with the Duck-Typing concept.

            – Eddie
            Nov 18 '18 at 11:52

















          Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

          – user2357112
          Nov 17 '18 at 0:23





          Or if getattr(session, 'var', None) is not None, to fuse the existence/None checks.

          – user2357112
          Nov 17 '18 at 0:23













          As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

          – Anthony
          Nov 17 '18 at 14:24





          As noted here, hasattr(session, 'var') is not necessary with the web2py session object, as it will simply return None for a non-existent key/property rather than raising an exception.

          – Anthony
          Nov 17 '18 at 14:24













          I was trying to avoid checking. Going with the Duck-Typing concept.

          – Eddie
          Nov 18 '18 at 11:52





          I was trying to avoid checking. Going with the Duck-Typing concept.

          – Eddie
          Nov 18 '18 at 11:52


















          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%2f53346918%2fpython-try-ing-not-to-repeat-code-try-except-and-else%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

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)