Last active
July 10, 2020 18:46
-
-
Save ddanier/a043e1dd0f2093e3c4efad43b6f61bf8 to your computer and use it in GitHub Desktop.
Python class_or_instance_method decorator, passes cls and self (if available)
This file contains hidden or 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 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