{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Decorators" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "def uppercase_decorator(function):\n", " def wrapper(*args,**kwargs):\n", " func = function(*args,**kwargs)\n", " make_uppercase = func.upper()\n", " return make_uppercase\n", " return wrapper" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "def func():\n", " return \"hello world\"" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "func = uppercase_decorator(func)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'HELLO WORLD'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "@uppercase_decorator\n", "def func1():\n", " return \"hello world 1\"" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'HELLO WORLD 1'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func1()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## timer example" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "from time import time,sleep\n", "\n", "def timeit(f):\n", " def wrapper(*args,**kwargs):\n", " start = time()\n", " val = f(*args,**kwargs)\n", " end = time()\n", " \n", " print(\"total time taken for this function :\",f.__name__,\" is\",end-start)\n", " return val\n", " return wrapper\n", "\n", "@timeit\n", "def slow_operation():\n", " sleep(3)\n", " return \"done\"" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total time taken for this function : slow_operation is 3.0030782222747803\n" ] }, { "data": { "text/plain": [ "'done'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "slow_operation()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.8.3 64-bit ('base': conda)", "language": "python", "name": "python383jvsc74a57bd01da5964c5502736b4e0a0c4398fb3b913682175f516e99bd48540f11726a612c" }, "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.8.3" }, "metadata": { "interpreter": { "hash": "1da5964c5502736b4e0a0c4398fb3b913682175f516e99bd48540f11726a612c" } } }, "nbformat": 4, "nbformat_minor": 4 }