def debug(*args):
    logging.debug('args: %s', args)
return args[0]

def monkeypatch():
    """
    allow StringIO to use `with` statement
    """
StringIO.__exit__ = debug
StringIO.__enter__ = debug
if __name__ == '__main__':
    monkeypatch()
with StringIO('this is a test') as infile:
    pass
Python StringIO плохо справляется с операторами `with`