Search code examples
pythonsocketspython-3.xexit

does socket __exit__ close in python?


I want to know if the:

with open_the_socket() as s:
    use s

works as intended. I read on another question that it would work provided that the socket's exit function calls for a close. It was said that 2.7 didn't, but I'm using 3.4 and I'm just wondering.


Solution

  • Here's a snippet from Python 3.4.0's socket.py:

    def __exit__(self, *args):
        if not self._closed:
            self.close()
    

    So, it closes the socket (as opposed to Python 2.7.10, where there's no __exit__ method for the socket object).

    Check [Python 3.4.Docs]: Data model - With Statement Context Managers for more details on context managers.

    Sample test code:

    >>>
    >>> import socket
    >>>
    >>>
    >>> s = None
    >>>
    >>> with socket.create_connection(("www.example.com", 80)) as s:
    ...     print(s._closed)
    ...
    False
    >>>
    >>> print(s._closed)
    True
    

    On Python 2, closing the socket could be forced (thanks @glglgl for the tip) using [Python 2.Docs]: contextlib.closing(thing):

    with contextlib.closing(open_the_socket()) as s:
        print(s)
        #use s