August 29, 2017

with statement in Python

□ File, database and network processing with a life cycle of start-process-end can be helped by "with".

□ At the start of the "with" statement, the __enter__ method is called.  It returns value to the variable given by "as". And at the end of the "with" statement, __exit__ method is called. It closes opened thing to end the life cycle.


※ Examples
with open("bcd.txt", "r") as f:
  for aData in f:
  print(aData)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sa:
  sa.connect((SERVER, PORT))
  sa.send(b"testing")
data = sa.recv(256)