Skip to content
Snippets Groups Projects

example_callable.py

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by David Kusterer

    This snippet exemplifies how to utilize abstract base classes and a Python classes "magic method" __call__() to formalize how to implement a family of functions that all have identical code that executes before and after some unique processing.

    Edited
    example_callable.py 1.39 KiB
    from abc import ABC, abstractmethod
    from typing import Any
    
    
    class BaseFunc(ABC):
        def checkArgs(self, x: Any):
            if isinstance(x, dict):
                if x.get("foo"):
                    pass
                else:
                    raise KeyError("No 'foo' in argument!")
            else:
                raise TypeError("Argument isn't a dict!")
    
        def checkReturns(self, y: Any):
            if isinstance(y, dict):
                if y.get("bar"):
                    pass
                else:
                    raise KeyError("No 'bar' in return value!")
            else:
                raise TypeError("Return value isn't a dict!")
    
        def __call__(self, unique_arg: dict):
            self.checkArgs(unique_arg)
            retval = self._uniqueLogic(unique_arg)
            self.checkReturns(retval)
            return retval
    
        @abstractmethod
        def _uniqueLogic(self, unique_arg: dict):
            raise NotImplementedError()
    
    
    class ImplementedFunc(BaseFunc):
        def _uniqueLogic(self, unique_arg: dict):
            return {"bar": unique_arg["foo"]}
    
    
    class BadImplementedFunc(BaseFunc):
        def _uniqueLogic(self, unique_arg: dict):
            return {"no_bar": unique_arg["foo"]}
    
    
    func = ImplementedFunc()
    
    badFunc = BadImplementedFunc()
    
    if __name__ == "__main__":
        print(func({"foo": 123}))
    
        try:
            func(123)
        except Exception as err:
            print(err)
    
        try:
            badFunc({"foo": 123})
        except Exception as err:
            print(err)
    0% or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment