Monday 24 August 2020

Python Callback for File Object Close

I am working on a custom file path class, which should always execute a function after the corresponding system file has been written to and its file object closed. The function will upload the contents of file path to a remote location. I want the upload functionality to happen entirely behind the scenes from a user perspective, i.e. the user can use the class just like any other os.PathLike class and automatically get the upload functionality. Psuedo code below for refernce.

import os

class CustomPath(os.PathLike):
    
    def __init__(self, remote_path: str):
        self._local_path = "/some/local/path"
        self._remote_path = remote_path

    def __fspath__(self) -> str:
        return self._local_path
    
    def upload(self):
        # Upload local path to remote path.

I can of course handle automatically calling the upload function for when the user calls any of the methods directly.

However, it unclear to me how to automatically call the upload function if someone writes to the file with the builtin open as follows.

custom_path = CustomPath("some remote location")

with open(custom_path, "w") as handle:
    handle.write("Here is some text.")

or

custom_path = CustomPath("some remote location")

handle = open(custom_path, "w")
handle.write("Here is some text.")
handle.close()

I desire compatibility with invocations of the open function, so that the upload behavior will work with all third party file writers. Is this kind of behavior possible in Python?



from Python Callback for File Object Close

No comments:

Post a Comment