qshinoの日記

Powershell関係と徒然なこと

Python with statement

with satement

with INSTANCE as VARIABLE:
  ...

example

with open(filename) as f:
  txt = f.read()
  print(txt)

with instance class

It should implement following methods.

__enter__(self)
__exit__(self, exception_type, exception_value, traceback)

class example

class WithExample:

  def __init__(self): 
    print('__init__') 

  def __del__(self): 
    print('__del__') 

  def __enter__(self): 
    print('__enter__') 
    #raise ValueError
    return self 

  def __exit__(self, et, ev, tb):
    print('__exit__') 
    self.close() 
    print(' exception:', et, ev)
    print(' traceback:', tb) 

  def close(self): 
    print(' close()') 

  def msg(self, msg): 
    print(msg) 

  def do():
    with WithExample() as we:
      # raise ValueError
      we.msg('in WithExample.') 

  def main(): 
    try: 
      do()
    except Exception as e: 
      print(f"Exception: {e}")
        
if __name__ == '__main__': 
  print("Begin")
  main()
  print("End")

example for db

import sqlite3 

con = sqlite3.connect(":memory:")
con.execute("create table foo (id integer primary key, name varchar unique)") 

# Successful, con.commit() is called automatically afterwards 

try:
  with con: 
    con.execute("insert into person(name) values (?)", ("Frau",)) 
    # con.rollback() when exception
    # exception must be catched
except Exception as e:
  print("Exception {e}")