Designing a dedicated python object that describes a file

I would like to create a class that describes a file resource, and then sort it. This part is simple. To be specific, let's say that I have a class “A” that has methods for working with a file. I can rekindle this object if it does not contain a file descriptor. I want to be able to create a file descriptor to access the resource described in "A". If I have an “open ()” method in class “A” that opens and saves a file descriptor for later use, then “A” is no longer legible. (I add here that opening a file includes some non-trivial indexes that cannot be cached - third-party code - so closing and reopening if necessary is not without cost). I could encode class "A" as a factory,which can generate file descriptors in the described file, but this can lead to simultaneous access of several files to access the contents of the file. I could use another class “B” to handle opening a file in class “A”, including locking, etc. I probably overdid it, but any tips would be appreciated.

+3
source share
3 answers

The question is not too clear; what it looks like:

  • you have a third-party module that has cool classes
  • these classes may contain links to files, which makes the classes themselves unusable because open files are not matched.

Essentially, you want to make open files picklable. You can do this quite easily, with a few caveats. Here's an incomplete but functional pattern:

import pickle
class PicklableFile(object):
    def __init__(self, fileobj):
        self.fileobj = fileobj

    def __getattr__(self, key):
        return getattr(self.fileobj, key)

    def __getstate__(self):
        ret = self.__dict__.copy()
        ret['_file_name'] = self.fileobj.name
        ret['_file_mode'] = self.fileobj.mode
        ret['_file_pos'] = self.fileobj.tell()
        del ret['fileobj']
        return ret

    def __setstate__(self, dict):
        self.fileobj = open(dict['_file_name'], dict['_file_mode'])
        self.fileobj.seek(dict['_file_pos'])
        del dict['_file_name']
        del dict['_file_mode']
        del dict['_file_pos']
        self.__dict__.update(dict)

f = PicklableFile(open("/tmp/blah"))
print f.readline()
data = pickle.dumps(f)
f2 = pickle.loads(data)
print f2.read()

Cautions and notes, some obvious, some less:

  • , open. - , gzip.GzipFile, , . , file.
  • , .
  • , .
  • ('w +'), , ; , , . - , - .
  • , IOError; , , .
  • Python 2 Python 3 ; file Python 3. Python 2 , file.

; , , , . , .

+6

, , , , .

, . , "" , .

?

+1

, , , , , . , , . ? , .

, . __getstate__. , , , , .

+1
source

Source: https://habr.com/ru/post/1773304/


All Articles