def __enter__(self):
    return self.fh

def __exit__(self, exc_type, exc_val, exc_tb):
    if self.closing:
        self.fh.close()
return False
How to accept both filenames and file-like objects in Python functions?