pythonpython-3.xsocketspython-2.xsix

Six's socket implementation


I build an app compatible between Python 2 and 3. In order to provide compatibility between those two Python versions, I use six library.

My code uses sockets. Under Python 3 it is possible to create them using with statement, but under Python 2 it claims on missing __exit__ attribute.

Is there any function of six providing disposable socket? If not, what solution would you consider as the most clear in this case?


Solution

  • AFAIK (by scanning through its docs) six doesn't do much in this case. In Python 2, you could wrap socket up in a context manager with the contextmanager decorator and supply that:

    from sys import version_info 
    import socket
    
    if version_info[0] == 2:
        from contextlib import contextmanager
    
        @contextmanager
        def sock(*args, **kwargs):
            s = socket.socket(*args, **kwargs)
            try:
                yield s
            finally:
                s.close()
    else:  # Python 3
        sock = socket.socket
    

    In both cases you use the with statement accordingly:

    with sock(socket.AF_INET, socket.SOCK_STREAM) as s:
        # use s