Skip to content

Instantly share code, notes, and snippets.

@thanakijwanavit
Created November 4, 2020 06:55
Show Gist options
  • Save thanakijwanavit/5d4041d756be13579c1e2edceb4f81be to your computer and use it in GitHub Desktop.
Save thanakijwanavit/5d4041d756be13579c1e2edceb4f81be to your computer and use it in GitHub Desktop.
wrap function to add method to a class
#export
from functools import wraps # This convenience func preserves name and docstring
def add_method(cls):
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
return func(self, *args, **kwargs)
setattr(cls, func.__name__, wrapper)
# Note we are not binding func, but wrapper which accepts self but does exactly the same as func
return func # returning func means func can still be used normally
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment