0

I'm learning socket programming in Python, and saw that a person used this piece of code:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()

Why would you use with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s instead of s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)? Is there any difference between these which makes one better to use in this case?

Gil Hamilton
  • 11,973
  • 28
  • 51
  • 2
    `with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:` is a context manger. If something unexpected like an error happens, it is designed to clean up the `socket` object (call `s.close()`, etc.) so you don't have to worry about it yourself. – Axe319 Jan 10 '22 at 18:41
  • Does this answer your question? [What is the purpose of a context manager in python](https://stackoverflow.com/questions/36559580/what-is-the-purpose-of-a-context-manager-in-python) – Ani Jan 10 '22 at 19:08
  • The `with` statement is a kind of assignment statement, but it's not (directly) assigning the socket to `s`; it's assigning the return value of the socket's `__enter__` method to `s`. – chepner Jan 10 '22 at 21:51

0 Answers0