Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zahlman
Created May 29, 2022 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zahlman/398bd9b8653f06f88a6a37ee44372f6a to your computer and use it in GitHub Desktop.
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
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