subclassing file objects (to extend open and close operations) in python 3

前端 未结 3 1885
北恋
北恋 2020-12-07 00:36

Suppose I want to extend the built-in file abstraction with extra operations at open and close time. In Python 2.7 this works:

cla         


        
3条回答
  •  萌比男神i
    2020-12-07 01:06

    I had a similar problem, and a requirement of supporting both Python 2.x and 3.x. What I did was similar to the following (current full version):

    class _file_obj(object):
        """Check if `f` is a file name and open the file in `mode`.
        A context manager."""
        def __init__(self, f, mode):
            if isinstance(f, str):
                self.file = open(f, mode)
            else:
                self.file = f
            self.close_file = (self.file is not f)
        def __enter__(self):
            return self
        def __exit__(self, *args, **kwargs):
            if (not self.close_file):
                return  # do nothing
            # clean up
            exit = getattr(self.file, '__exit__', None)
            if exit is not None:
                return exit(*args, **kwargs)
            else:
                exit = getattr(self.file, 'close', None)
                if exit is not None:
                    exit()
        def __getattr__(self, attr):
            return getattr(self.file, attr)
        def __iter__(self):
            return iter(self.file)
    

    It passes all calls to the underlying file objects and can be initialized from an open file or from a filename. Also works as a context manager. Inspired by this answer.

提交回复
热议问题