{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n==============================================================================\nExample: decorating specified methods of a custom class with custom decorators\n==============================================================================\n\nThis example shows how to decorate methods of a custom class with custom\ndecorators.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import time\n\nfrom pydeco import Decorator, MethodsDecorator"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create timer decorator\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class Timer(Decorator):\n    \"\"\"Timer decorator.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.run = 0\n        self.run_by_func = dict()\n        self.total_runtime = 0\n        Decorator.__init__(self, *args, **kwargs)\n\n    def __repr__(self):\n        \"\"\"Return the string representation.\"\"\"\n        return ('Timer(run={}, run_by_func={}, total_runtime={:2.2f} ms)'\n                .format(self.run, self.run_by_func, self.total_runtime))\n\n    def wrapper(self, instance, func, *args, **kwargs):\n        \"\"\"Wrap input instance method with runtime measurement.\"\"\"\n        # increment run attributes\n        self.run += 1\n        if func.__name__ not in self.run_by_func:\n            self.run_by_func[func.__name__] = 1\n        else:\n            self.run_by_func[func.__name__] += 1\n\n        # save current time\n        ts = time.time()\n\n        # call `func` on inputs\n        outs = func(instance, *args, **kwargs)\n\n        # compute elapsed time\n        te = time.time()\n        runtime = (te - ts) * 1000\n        # Update total runtime of timer\n        self.total_runtime += runtime\n\n        print('[Log] runtime {!r} : {:2.2f} ms'.format(func.__name__, runtime))\n\n        # return outputs of `func`\n        return outs"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create custom decorators\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class Decorator1(Decorator):\n    \"\"\"Decorator 1.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        Decorator.__init__(self, *args, **kwargs)\n\n    def wrapper(self, instance, func, *args, **kwargs):\n        \"\"\"Wrap input instance method with the herebelow code.\"\"\"\n        print('[Decorator 1] -> decorating {}.{}'.format(\n            instance._Wrapper__wrapped_class.__name__, func.__name__))\n        return func(instance, *args, **kwargs)\n\n\nclass Decorator2(Decorator):\n    \"\"\"Decorator 2.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        Decorator.__init__(self, *args, **kwargs)\n\n    def wrapper(self, instance, func, *args, **kwargs):\n        \"\"\"Wrap input instance method with the herebelow code.\"\"\"\n        print('[Decorator 2] -> decorating {}.{}'.format(\n            instance._Wrapper__wrapped_class.__name__, func.__name__))\n        return func(instance, *args, **kwargs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create custom class\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "timer = Timer()\n\n\nclass MyClass():\n    \"\"\"Custom class.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        pass\n\n    @timer\n    def method_1(self, *args, **kwargs):\n        print('Run method 1')\n\n    @timer\n    def method_2(self, *args, **kwargs):\n        print('Run method 2')\n\n    @timer\n    def method_3(self, *args, **kwargs):\n        print('Run method 3')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Test\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Without custom decorators\n# -----------------------------------------------------------------------------\n\n# instantiate the class\ninstance = MyClass()\n\n# run methods\ninstance.method_1()\ninstance.method_2()\ninstance.method_3()\n\n# With custom decorators for the respective methods\n# -----------------------------------------------------------------------------\n\n# decorate the class\nMyClass_deco = MethodsDecorator(\n    mapping={\n        Decorator1(): ['method_1', 'method_2'],\n        Decorator2(): ['method_1', 'method_3']\n    })(MyClass)\n\n# instantiate the class\ninstance = MyClass_deco()\n\n# run methods\ninstance.method_1()\ninstance.method_2()\ninstance.method_3()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}