from functools import reduce
class ExtraHeaders(object):

    def __init__(self, br, headers):
        self.extra_headers = headers
self.br = br

def __enter__(self):
    self.old_headers = self.br.addheaders
self.br.addheaders = self.extra_headers + [h for h in self.br.addheaders if
    not reduce(lambda accum, ex_h: accum or ex_h[0] == h[0], self.
    extra_headers, False)]
return self.br

def __exit__(self, type, value, traceback):
    self.br.addheaders = self.old_headers
Python Mechanize - how to add a header on a single .open() call?