{ "cells": [ { "cell_type": "markdown", "id": "4217c5b9", "metadata": {}, "source": [ "# Python Basics - 11. Scope, Closures, and Decorators\n", "\n", "This notebook explains variable scope (LEGB), closures, and decorators. These topics are key to understanding how Python functions behave in real projects." ] }, { "cell_type": "markdown", "id": "01488228", "metadata": { "language": "markdown" }, "source": [ "## Download Notebook\n", "\n", "{download}`Download this notebook <11_scope_closures_and_decorators.ipynb>`\n" ] }, { "cell_type": "markdown", "id": "eee44670", "metadata": {}, "source": [ "## 1. LEGB Scope Rule\n", "\n", "Python resolves names in this order: Local, Enclosing, Global, Built-in." ] }, { "cell_type": "code", "execution_count": null, "id": "8dda99f4", "metadata": {}, "outputs": [], "source": [ "message = \"global\"\n", "\n", "def outer():\n", " message = \"enclosing\"\n", " def inner():\n", " message = \"local\"\n", " print(f\"Inner sees: {message}\")\n", " inner()\n", " print(f\"Outer sees: {message}\")\n", "\n", "outer()\n", "print(f\"Global sees: {message}\")" ] }, { "cell_type": "markdown", "id": "8dff8819", "metadata": {}, "source": [ "## 2. Closures\n", "\n", "A closure is an inner function that remembers values from its enclosing scope even after the outer function returns." ] }, { "cell_type": "code", "execution_count": null, "id": "5917e504", "metadata": {}, "outputs": [], "source": [ "def make_multiplier(factor):\n", " def multiply(x):\n", " return x * factor\n", " return multiply\n", "\n", "double = make_multiplier(2)\n", "triple = make_multiplier(3)\n", "print(double(10), triple(10))" ] }, { "cell_type": "markdown", "id": "a29340e7", "metadata": {}, "source": [ "## 3. Decorators\n", "\n", "A decorator wraps a function to add behavior before/after execution without changing the original function body." ] }, { "cell_type": "code", "execution_count": null, "id": "13ea09d9", "metadata": {}, "outputs": [], "source": [ "def log_call(func):\n", " def wrapper(*args, **kwargs):\n", " print(f\"Calling {func.__name__} with args={args}, kwargs={kwargs}\")\n", " result = func(*args, **kwargs)\n", " print(f\"{func.__name__} returned {result}\")\n", " return result\n", " return wrapper\n", "\n", "@log_call\n", "def add(a, b):\n", " return a + b\n", "\n", "add(5, 7)" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }