Home > Back-end >  Overriding a method when creating a new object
Overriding a method when creating a new object

Time:01-12

I'm using the Watchdog library to monitor different folders. There are two folders with two different behaviors:

  1. In folder alpha, when a new file is created, move it to destination_alpha.
  2. In folder beta, when a new file is created, pass it to a method.

Here's the code snippet for the first behavior:

import shutil
from watchdog.events import FileSystemHandler
from watchdog.observers import Observer

class FolderWatcher(FileSystemEventHandlder):
    '''Overrides the on_created method to take action when a file is created.'''
    def on_created(self, event):
        shutil.move(event.src_path, '/destination_alpha')
event_handler = FolderWatcher()
folder_alpha_observer = Observer()
folder_alpha_observer.schedule(event_handler,'/folder_alpha')
try:
    while True:
    time.sleep(1)
finally: 
    folder_alpha_observer.stop()
    folder_alpha_observer.join()

Can I reuse the same class for another FolderWatcher object with different behavior in the on_created method? Or do I need to create a new FolderWatcher-ish class with a different on_created method?

class SecondFolderWatcher(FileSystemEventHandlder):
    '''Overrides the on_created method to take action when a file is created.'''
    def on_created(self, event):
        imported_method(event.src_path)
second_folder_watcher = SecondFolderWatcher()
folder_beta_observer = Observer()
folder_beta_observer.schedule(second_folder_watcher,'/folder_alpha')
try:
    while True:
    time.sleep(1)
finally: 
    folder_alpha_observer.stop()
    folder_alpha_observer.join()

This doesn't seem very elegant, creating a whole new class for every on_created action I want to take. But I don't see a better way to do it. Your thoughts?

CodePudding user response:

You could always inject a callback function:

class FolderWatcher(FileSystemEventHandlder):
    '''Overrides the on_created method to take action when a file is created.'''
    def __init__(self, on_created_cb):
        super().__init__()
        self._on_created_cb = on_created_cb

    def on_created(self, event):
        self._on_created_cb(event)

event_handler = FolderWatcher(
    lambda event: shutil.move(event.src_path, '/destination_alpha')
)
second_folder_watcher = FolderWatcher(
    lambda event: imported_method(event.src_path)
)
# etc
  • Related