Skip to content

Instantly share code, notes, and snippets.

@ddanier
Last active July 10, 2020 18:46
Show Gist options
  • Save ddanier/a043e1dd0f2093e3c4efad43b6f61bf8 to your computer and use it in GitHub Desktop.
Save ddanier/a043e1dd0f2093e3c4efad43b6f61bf8 to your computer and use it in GitHub Desktop.
Python class_or_instance_method decorator, passes cls and self (if available)
from typing import Callable, Type
import functools
class class_or_instance_method:
func: Callable
def __init__(self, func: Callable):
self.func = func
def __get__(self, instance: object, owner: Type = None):
if owner is None and instance:
owner = instance.__class__
@functools.wraps(self.func)
def _func(*args, **kwargs):
return self.func(
owner,
instance,
*args,
**kwargs,
)
return _func
# Usage:
# class Foo:
# @class_or_instance_method
# def test(cls, self, *args, **kwargs):
# print(cls)
# print(self)
# print(args)
# print(kwargs)
# Foo.test()
# Foo().test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment