python2.6 features / python2.5

  • Written by Walter Doekes

  • Published on: 2010-06-19

Today I’ll show you some quick and dirty python2.5 compatibility fixes. Of course you’re developing on python2.6 or even python3.x, but your customer still lives in the dark ages. Here are two fixes that might come in handy.

ImportError: No module named ssl

Falling back to python2.5 socket.SSL if there is no python2.6 ssl through a small wrap_socket replacement:

import socket
    from ssl import wrap_socket
except ImportError:
    class wrap_socket:
        def __init__(self, socket):
            self.socket = socket
        def __getattr__(self, name):
            return getattr(self.socket, name)
        def connect(self, *args, **kwargs):
            self.socket.connect(*args, **kwargs)
            self.ssl = socket.ssl(self.socket)
        def read(self, *args, **kwargs):
            return*args, **kwargs)
        recv = read
        def write(self, *args, **kwargs):
            return self.ssl.write(*args, **kwargs)
        send = write

AttributeError: ‘unicode’ object has no attribute ‘format’

Falling back to python2.5 Template if there is no python2.6 string.format. It does not do any fancy formatting, but in many cases you’re not using that either. (Yes, for template syntax, {variable} wins in readability over $variable or, even worse, %(variable)s.)

if not hasattr('', 'format'):
    from string import Template
    import re
    def str_format(string, *args, **kwargs):
        tpl = Template(string)
        tpl.pattern =
        return tpl.substitute(*args, **kwargs) = re.compile(r'\{(?P<named>[A-Za-z0-9_]+)\}')


    value = template.format(**values)
except AttributeError:
    value = str_format(template, **values)

Back to overview Newer post: altgr / nxclient / compose key Older post: uninitialized globals / C language