{ "metadata": { "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 }, "orig_nbformat": 2 }, "nbformat": 4, "nbformat_minor": 2, "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from contextlib import contextmanager" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def my_decorator(fn):\n", " \"\"\"\n", " This is my decorator.\n", " \"\"\"\n", " def wrapper(*args, **kwargs):\n", " \"\"\"\n", " This is the wrapper.\n", " \"\"\"\n", " return 42\n", " return wrapper\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "@my_decorator\n", "def thing(arg):\n", " \"\"\"\n", " Thing which is decorated.\n", " \"\"\"\n", " pass\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "@contextmanager\n", "def my_context_manager():\n", " \"\"\"\n", " This is my context manager.\n", " \"\"\"\n", " print(\"before\")\n", " yield\n", " print(\"after\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with my_context_manager():\n", " thing(19)" ] } ] }