Created
January 20, 2024 15:07
-
-
Save CyanChanges/1cc00e56b8f4405c89ea0dfb38e9926a to your computer and use it in GitHub Desktop.
Python simple HMR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import functools | |
| from threading import Timer | |
| def debounce(wait): | |
| """ Decorator that will postpone a functions | |
| execution until after wait seconds | |
| have elapsed since the last time it was invoked. """ | |
| def decorator(fn): | |
| def debounced(*args, **kwargs): | |
| @functools.wraps(fn) | |
| def call_it(): | |
| fn(*args, **kwargs) | |
| try: | |
| debounced.t.cancel() | |
| except AttributeError: | |
| pass | |
| debounced.t = Timer(wait, call_it) | |
| debounced.t.start() | |
| return debounced | |
| return decorator |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import importlib | |
| import atexit | |
| from watchdog.observers import Observer | |
| from watchdog.events import FileSystemEventHandler, FileModifiedEvent | |
| from debounce import debounce | |
| class HMRHandler(FileSystemEventHandler): | |
| def __init__(self, module, hmr_obj): | |
| super().__init__() | |
| self.module = module | |
| self.hmr_obj = hmr_obj | |
| @debounce(2) | |
| def on_modified(self, event: FileModifiedEvent): | |
| try: | |
| self.hmr_obj.__module__ = importlib.reload(self.module) | |
| except ImportError: | |
| pass | |
| def hmr(module): | |
| module_file = module.__file__ | |
| observer = Observer() | |
| hmr_obj = type('HMRObject', (), { | |
| "__module__": module, | |
| "__getattribute__": lambda self, p: getattr(type(self).__module__, p) | |
| }) | |
| observer.schedule(HMRHandler(module, hmr_obj), module_file) | |
| observer.start() | |
| atexit.register(observer.stop) | |
| return hmr_obj() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment