The universal approach is to dynamically choose an opener
:
openers = {
'http': urllib2.urlopen,
'.csv.gz': gzip.open
'.csv': open
}
resource_type = get_resource_type(resource) # determine the type of the resource
with openers[resource_type](resource) as f:
# do stuff ...
That way, you can painlessly add more openers, when needed. Here is another example of the factory method design pattern.