Source code for devctrl.utility.decorators

class ClassOrInstanceMethod:
    """Decorator to make a class member function a class or instance method, depending on how it is called.

    The first argument will always be the class (usually called cls for class methods). 
    If the method is called from an instance, the instance will be added as keyword argument 'instance'.

    Example:

        class Test:
            def __init__(self, name):
                self.name = name

            @ClassOrInstanceMethod
            def test(cls, instance=None):
                if instance is None:
                    print("Called from class")
                else:
                    print(f"Called from instance {instance.name}")

        t = Test("#1")
        t.test()
        Test.test()
                
    """
    def __init__(self, f):
        self.f = f

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args, **kw):
            # If called on the class, pass the class as first argument
            if obj is None:
                return self.f(klass, *args, **kw)
            # If called on an instance, pass both the class and the instance
            else:
                return self.f(klass, *args, **(kw | dict(instance=obj)))
        return newfunc