The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Python FAQ: How fast are exceptions? Is exception handling efficient in Python? (Python Tutorial: Using Try/Except Blocks for Error Handling)
By Guest on 9th November 2022 12:12:27 AM | Syntax: PYTHON | Views: 178



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. Is exception handling efficient in Python?
  2. How efficient is try except?
  3. Should you use exceptions in Python?
  4.  
  5.  
  6. How fast are exceptions?
  7. ========================
  8.  
  9. A try/except block is extremely efficient if no exceptions are raised.
  10. Actually catching an exception is expensive.  In versions of Python
  11. prior to 2.0 it was common to use this idiom:
  12.  
  13.    try:
  14.        value = mydict[key]
  15.    except KeyError:
  16.        mydict[key] = getvalue(key)
  17.        value = mydict[key]
  18.  
  19. This only made sense when you expected the dict to have the key almost
  20. all the time.  If that wasn't the case, you coded it like this:
  21.  
  22.   if key in mydict:
  23.       value = mydict[key]
  24.   else:
  25.       value = mydict[key] = getvalue(key)
  26.  
  27. For this specific case, you could also use "value =
  28. dict.setdefault(key, getvalue(key))", but only if the "getvalue()"
  29. call is cheap enough because it is evaluated in all cases.
  30.  
  31. Exception handling tips in Python ⚠ Write better Python code




  32.  
  33. Python Tutorial: Using Try/Except Blocks for Error Handling
  34.  
  35. [inline]
















Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.

Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license
  • Recent Pastes