Skip to content

Instantly share code, notes, and snippets.

@funketh
Created December 3, 2019 22:09
Show Gist options
  • Save funketh/8b4eaf72ac02d6072e987e4ee16cf109 to your computer and use it in GitHub Desktop.
Save funketh/8b4eaf72ac02d6072e987e4ee16cf109 to your computer and use it in GitHub Desktop.
Decorator to add functions as methods to a class (Note: This is basically useless as you can just use `method_name = function` inside the class body)
from typing import TypeVar, Union, Callable, Optional
_ClsT = TypeVar('_ClsT', bound=type)
def add_method(func: Union[Callable, classmethod, staticmethod],
name: Optional[str] = None) -> Callable[[_ClsT], _ClsT]:
"""Class decorator that adds the given function as a method to the class"""
def decorator(cls: _ClsT) -> _ClsT:
nonlocal name
if name is not None:
pass
elif isinstance(func, classmethod) or isinstance(func, staticmethod):
name = func.__func__.__name__
else:
name = func.__name__
if hasattr(cls, name):
raise ValueError(f'method name conflict: {name}')
setattr(cls, name, func)
return cls
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment