omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Another Doh! Lesson Learned

    Pythonista
    3
    4
    2164
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • adrius42
      adrius42 last edited by adrius42

      My program was creating extra ‘-‘ characters, I spent ages looking in other parts of the code for the extra character creator.

      The lesson “ Don’t make stupid mistakes inside ‘try:’ code

      Like this one

      try:
      	with open(self.fp_files[hd], 'r')	as f: # fp_files loaded in setup
      		self.fastestplayers.append(f.read())
      		print('during opening', hd, self.fastestplayers(hd))
      except:
      	self.fastestplayers.append('-')
      

      The stupid thing was I forgot I had added the print command to follow the logic.
      Hence I didn’t miss it!

      Of course the () rather than [] in the superfluous print line created an error that triggered the exception code.

      Hence the extra ‘-‘

      Shared to help others look more carefully for stupid mistakes inside “try” code, after all you have told the interpreter you will handle errors in there!
      ...

      JonB 1 Reply Last reply Reply Quote 0
      • JonB
        JonB @adrius42 last edited by

        Another lesson might be to avoid the try/except anti pattern.

        If you had caught only the errors that could be thrown by open or read

        except (IOError, OSError):
        

        Then errors inside the try that you were not expecting still get raised. Or maybe you want to catch only FileNotFoundError, but you get the idea -- catch only the errors you expect can happen.

        1 Reply Last reply Reply Quote 0
        • ccc
          ccc last edited by

          Agreed. The anitpattern is the bare except: https://realpython.com/the-most-diabolical-python-antipattern/

          1 Reply Last reply Reply Quote 0
          • adrius42
            adrius42 last edited by adrius42

            Thanks guys for the specific pointer, ‘catch just the exception you WANT to catch”

            AND THE GREAT READ, which reinforced the importance of the specific pointer above, as well as fully Logging exception events.

            The Doh! lesson is now learnable at a great new depth...

            I now only except “FileNotFoundError”

            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors