Question

I want my code to suuport python >= 2.5 The code uses urllib like this:

handle = urllib2.urlopen(req, timeout)

This worked fine for python2.6 & python2.7 but python2.5 does not support explicit timeout so we have to set default timeout for sockets like this:

import socket
socket.setdefaulttimeout(timeout)
handle = urllib2.urlopen(req)

Although this works fine for higher versions of python (2.6 & 2.7) but I want to set timeout explicitly where it is supported. My question is how to do this elegantly? Should I do a version check?

Was it helpful?

Solution

There's always try, which is pretty much perfect for this sort of thing:

import socket
import urllib2

try:
    handle = urllib2.urlopen(req, timeout = timeout)
except TypeError:
    socket.setdefaulttimeout(timeout)
    handle = urllib2.urlopen(req)

(Make sure to use the keyword argument for this in the first call, otherwise python 2.5 will think you are passing it the 'data' argument.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top