Search notes:

Python: __exit__

Parameterse

Besides the ubiquitous self parameter, __exit__ also takes three additional parameters
The additional parameters are only releveant and distinct from None when __exit__ is called because an exception was raised after __enter__ was called. In such a case, the three parameters have the following meaning:
The following example tries to demonstrate these parameters:
class Ex(Exception):

  def __init__(self, text):
      self.text = text

  def __str__(self):
      return self.text

class RES:

  def __enter__(self):
      print('__enter__')
      return self

  def __exit__(self, exType, exValue, traceBack):
      print(f'__exit__, exType: {str(exType)}, exValue: {str(exValue)}, traceBack: {str(traceBack)}')


try:

  print('')

  with RES():
       print('  A')

  print('')

  with RES():
       print('  B')
       raise Ex('Something bad')

except Ex as ex:
       print('')
       print(f'Caught exception {str(ex)}')
Github repository about-Python, path: /dunders/__exit__/parameters.py
When executed, the script prints
__enter__
  A
__exit__, exType: None, exValue: None, traceBack: None

__enter__
  B
__exit__, exType: <class '__main__.Ex'>, exValue: Something bad, traceBack: <traceback object at 0x000002C0AFC400C0>

Caught exception Something bad

See also

The with statement
Context managers and the __enter__ method.
Other dunders

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759397210, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/dunders/__exit__(101): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78