-
-
Save zahlman/398bd9b8653f06f88a6a37ee44372f6a to your computer and use it in GitHub Desktop.
Example of prebound method pattern (https://python-patterns.guide/python/prebound-methods/) using lazily loaded global instance
This file contains 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
from functools import partial | |
_implementation = None | |
def _determine_filename(): | |
# logic to decide on a filename for an underlying resource, or None | |
... | |
def load_implementation(filename=None): | |
# logic to find an implementation, either returning it or raising an exception | |
if filename is None: | |
filename = _determine_filename() | |
if filename is None: | |
# adjust exception as appropriate | |
raise RuntimeError("implementation could not be found") | |
... | |
# meta magic to generate wrappers for methods of the lazily loaded implementation. | |
def _wrapper(attrname, *args, implementation_src=None, **kwargs): | |
if _implementation is None: | |
_implementation = load_implementation(implementation_src) | |
elif implementation_src is not None: | |
... # could raise an exception, or replace the implementation, or ignore it | |
return getattr(_implementation, attrname)(*args, **kwargs) | |
# example of exposing a method | |
example_action = partial(_wrapper, 'example_action') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment