@@ -828,6 +828,52 @@ def clear(self):
828828 self .maps [0 ].clear ()
829829
830830
831+ # Re-use the same sentinel as in the Python stdlib socket module:
832+ from socket import _GLOBAL_DEFAULT_TIMEOUT
833+ # Was: _GLOBAL_DEFAULT_TIMEOUT = object()
834+
835+
836+ def create_connection (address , timeout = _GLOBAL_DEFAULT_TIMEOUT ,
837+ source_address = None ):
838+ """Backport of 3-argument create_connection() for Py2.6.
839+
840+ Connect to *address* and return the socket object.
841+
842+ Convenience function. Connect to *address* (a 2-tuple ``(host,
843+ port)``) and return the socket object. Passing the optional
844+ *timeout* parameter will set the timeout on the socket instance
845+ before attempting to connect. If no *timeout* is supplied, the
846+ global default timeout setting returned by :func:`getdefaulttimeout`
847+ is used. If *source_address* is set it must be a tuple of (host, port)
848+ for the socket to bind as a source address before making the connection.
849+ An host of '' or port 0 tells the OS to use the default.
850+ """
851+
852+ host , port = address
853+ err = None
854+ for res in getaddrinfo (host , port , 0 , SOCK_STREAM ):
855+ af , socktype , proto , canonname , sa = res
856+ sock = None
857+ try :
858+ sock = socket (af , socktype , proto )
859+ if timeout is not _GLOBAL_DEFAULT_TIMEOUT :
860+ sock .settimeout (timeout )
861+ if source_address :
862+ sock .bind (source_address )
863+ sock .connect (sa )
864+ return sock
865+
866+ except error as _ :
867+ err = _
868+ if sock is not None :
869+ sock .close ()
870+
871+ if err is not None :
872+ raise err
873+ else :
874+ raise error ("getaddrinfo returns an empty list" )
875+
876+
831877# Back up our definitions above in case they're useful
832878_OrderedDict = OrderedDict
833879_Counter = Counter
@@ -837,13 +883,15 @@ def clear(self):
837883__count_elements = _count_elements
838884_recursive_repr = recursive_repr
839885_ChainMap = ChainMap
886+ _create_connection = create_connection
840887
841888# Overwrite the definitions above with the usual ones
842889# from the standard library:
843890if sys .version_info >= (2 , 7 ):
844891 from collections import OrderedDict , Counter
845892 from subprocess import check_output
846893 from itertools import count
894+ from socket import create_connection
847895
848896if sys .version_info >= (3 , 0 ):
849897 from math import ceil
0 commit comments