惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Spread Privacy
Spread Privacy
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
P
Privacy & Cybersecurity Law Blog
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
T
Tenable Blog
TaoSecurity Blog
TaoSecurity Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
AI
AI
P
Proofpoint News Feed
A
About on SuperTechFans
P
Privacy International News Feed
月光博客
月光博客
雷峰网
雷峰网
S
Secure Thoughts
博客园 - 叶小钗
博客园 - 聂微东
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Project Zero
Project Zero
The Cloudflare Blog
SecWiki News
SecWiki News
The Hacker News
The Hacker News
V
Vulnerabilities – Threatpost
罗磊的独立博客
A
Arctic Wolf
阮一峰的网络日志
阮一峰的网络日志
Know Your Adversary
Know Your Adversary
酷 壳 – CoolShell
酷 壳 – CoolShell
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Troy Hunt's Blog
The Last Watchdog
The Last Watchdog
Schneier on Security
Schneier on Security
小众软件
小众软件
有赞技术团队
有赞技术团队
博客园 - 司徒正美
T
Tailwind CSS Blog
量子位
C
Cybersecurity and Infrastructure Security Agency CISA
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
L
Lohrmann on Cybersecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
🐍 python global vs nonlocal keyword — when to use each?
Python-T Poi · 2026-05-21 · via DEV Community

A variable can be modified inside a nested function without being passed as an argument — if Python’s scope resolution rules allow it through global or nonlocal.

📑 Table of Contents

  • 🧠 Scopes in Python — How Names Are Resolved
  • 🌍 Global — Modifying Module-Level Names
  • ⚙️ Mechanism — What Happens at Compile Time
  • 📌 Practical Example — A Simple Call Counter
  • ⚠️ Gotcha — Global Isn’t Always What You Want
  • 🔐 Nonlocal — Accessing Enclosing Function Variables
  • ⚙️ Mechanism — Cell Variables and Closure
  • 📌 Practical Example — Maintaining State in a Closure
  • 💡 Real-World Use Case — Retry Logic with Backoff
  • 🔍 Python Global vs Nonlocal Keyword — Key Differences
  • 🎯 Scope Target
  • 📌 Assignment Behavior
  • 🧪 Name Resolution Flow
  • 🧠 Memory Implications — Closures and Reference Counting
  • 🧱 When to Use Each — Best Practices
  • ✅ Use global When:
  • ✅ Use nonlocal When:
  • 🚫 Avoid Both When:
  • 🔍 Rule of Thumb
  • 🟩 Final Thoughts
  • ❓ Frequently Asked Questions
  • Can I use both global and nonlocal in the same function?
  • Why do I get UnboundLocalError when I didn’t use global or nonlocal?
  • Does nonlocal work with nested classes or only functions?
  • 📚 References & Further Reading

🧠 Scopes in Python — How Names Are Resolved

Python resolves names using the LEGB rule : Local → Enclosing → Global → Built-in. This governs read operations: when you reference x, Python checks these scopes in order. At function definition time, the compiler scans all assignments. If any statement assigns to a name (e.g., x = 1, x += 1), that name is classified as local to the function unless declared otherwise with global or nonlocal. This means assignment changes the scope interpretation of a name—even if the assignment comes after a read.

x = "global" def outer(): x = "enclosing" def inner(): print(x) # Which x? LEGB says: look in enclosing inner() outer() # Output: enclosing

Enter fullscreen mode Exit fullscreen mode

Now consider modifying x in inner():

def outer(): x = "enclosing" def inner(): x = "local" # Creates new local x — doesn't touch outer x print(x) inner() print(x) outer()
# Output:
# local
# enclosing

Enter fullscreen mode Exit fullscreen mode

The assignment in inner() binds x locally. To mutate the x in outer, you must declare intent with nonlocal.


🌍 Global — Modifying Module-Level Names

The global keyword binds a name to the module-level namespace (globals()), regardless of nesting depth. This enables shared state across functions in the same module—useful for debug flags, registries, or process-wide counters. The mechanism is straightforward: when the compiler sees global x, it treats all references to x as module-scoped.

⚙️ Mechanism — What Happens at Compile Time

During compilation, Python builds a symbol table for each function. A global declaration forces a name to be resolved via the current module’s **dict**, bypassing local and enclosing scopes entirely. Writes go directly to the module namespace. Reads pull from it. No cell objects are created; there’s no closure involvement.

📌 Practical Example — A Simple Call Counter

call_count = 0 def api_request(url): global call_count call_count += 1 print(f"Fetching {url} (call #{call_count})") # simulate request... def retry_request(url, retries=3): for i in range(retries): api_request(url) retry_request("https://httpbin.org/status/500")
# Output:
# Fetching https://httpbin.org/status/500 (call #1)
# Fetching https://httpbin.org/status/500 (call #2)
# Fetching https://httpbin.org/status/500 (call #3)

Enter fullscreen mode Exit fullscreen mode

Without global, call_count += 1 would raise UnboundLocalError. The compound assignment implies local binding, yet the initial read fails because no local value exists yet.

⚠️ Gotcha — Global Isn’t Always What You Want

Using global couples functions to module state, reducing testability and increasing side-effect surface. It also introduces race conditions under concurrency unless external synchronization is applied.

def bad_idea(): global temp_result temp_result = "something" # Pollutes module namespace

Enter fullscreen mode Exit fullscreen mode

Prefer return values or class attributes for intermediate data. Reserve global for genuine module-level state.


🔐 Nonlocal — Accessing Enclosing Function Variables

nonlocal allows a nested function to modify a variable in its immediate enclosing function scope. It's the only way to rebind names from outer function locals while preserving encapsulation. This is essential for stateful closures—like decorators, retries, or factory functions—where you need mutable upvars without resorting to classes.

⚙️ Mechanism — Cell Variables and Closure

When an inner function references a variable from an outer function, Python wraps that variable in a cell object (cell_contents). Multiple nested functions can share access to the same cell. nonlocal instructs the compiler to bind assignments to the existing cell in the nearest enclosing scope. This creates a true closure: the outer variable persists beyond the lifetime of the outer function, as long as references exist.

📌 Practical Example — Maintaining State in a Closure

This pattern is common in functional utilities:

def make_counter(): count = 0 # Local to make_counter def increment(): nonlocal count count += 1 return count return increment counter_a = make_counter()
counter_b = make_counter() print(counter_a()) # 1
print(counter_a()) # 2
print(counter_b()) # 1 — independent state

Enter fullscreen mode Exit fullscreen mode

Without nonlocal, count += 1 would trigger UnboundLocalError. The variable is visible due to LEGB, but assignment creates a local by default, shadowing the closure binding.

💡 Real-World Use Case — Retry Logic with Backoff

import time def exponential_retry(max_retries=3): attempt = 0 delay = 1 def should_retry(func): nonlocal attempt, delay while attempt < max_retries: try: return func() except Exception as e: attempt += 1 print(f"Attempt {attempt} failed: {e}, retrying in {delay}s") time.sleep(delay) delay *= 2 # Exponential backoff raise RuntimeError("Max retries exceeded") return should_retry # Usage
network_call = exponential_retry(max_retries=3)(lambda: requests.get("https://httpbin.org/status/500"))

Enter fullscreen mode Exit fullscreen mode

nonlocal enables stateful retry logic without global variables or class instantiation. The closure captures attempt and delay in cells, allowing mutation across invocations.

Use global to modify module state, nonlocal to modify closure state — never use either for temporary values.


🔍 Python Global vs Nonlocal Keyword — Key Differences

The python global vs nonlocal keyword difference lies in the target scope and resolution path.

🎯 Scope Target

- global: binds to the module-level namespace (globals()).

- nonlocal: binds to the nearest enclosing function’s local scope—must be a function, not module or class scope. Using nonlocal on a global name raises SyntaxError:

x = "global" def outer(): def inner(): nonlocal x # SyntaxError: no binding for nonlocal 'x' found

Enter fullscreen mode Exit fullscreen mode

Because x exists in the global scope, not a function enclosure. The compiler finds no matching name in any enclosing function scope, so the declaration is invalid.

📌 Assignment Behavior

Both keywords allow mutation of outer scopes otherwise accessible only for reading. Only nonlocal enables closure mutation , supporting functional patterns like memoization, configuration factories, or stateful decorators.

🧪 Name Resolution Flow

For x = 5 in a function: 1. Compiler checks for global x → binds to module scope.

2. Else, checks for nonlocal x → binds to enclosing function’s cell.

3. Else, creates or overwrites x in local scope. For reading x: 1. Runtime searches: Local → Enclosing → Global → Built-in (LEGB).

2. nonlocal does not alter read behavior—only assignment binding. This explains why reads are permitted freely, but writes require explicit scope declaration.

def outer(): x = "enclosing" def inner(): print(x) # OK — read allowed # x = "local" # Uncommenting breaks the read above inner()

Enter fullscreen mode Exit fullscreen mode

Once x is assigned, it becomes local. The preceding print(x) tries to access a local x before it's defined—hence the UnboundLocalError if the assignment were active.

🧠 Memory Implications — Closures and Reference Counting

Variables captured by nonlocal are stored in cell objects that remain alive as long as any referencing closure exists. This prevents the outer function’s frame from being garbage-collected prematurely. In long-running processes with many dynamically generated closures—such as async task factories or middleware chains—this can accumulate memory. The effect is expected and usually negligible, but becomes measurable when thousands of closures retain references to large outer variables. Consider limiting captured data size or using weak references when appropriate.


🧱 When to Use Each — Best Practices

Choice between global and nonlocal should reflect intent and isolation needs.

✅ Use global When:

- Maintaining process-wide state like debug flags, logging levels, or feature toggles.

- Writing scripts where module scope is the natural state container.

- Implementing registries or singletons (with caution—prefer classes). Avoid global in reusable libraries; it undermines composability and makes unit testing harder.

✅ Use nonlocal When:

- Building stateful closures: counters, accumulators, retry trackers.

- Writing decorators that need internal state.

- Returning callable factories with private mutable state. It's safer than global because state is encapsulated within function closures, not exposed at module level.

🚫 Avoid Both When:

- A class would make state and behavior clearer.

- Return values and reassignment suffice.

- Temporaries are involved—use locals. Classes offer better extensibility and debugging affordance:

class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 return self.count

Enter fullscreen mode Exit fullscreen mode

This is more explicit than a closure with nonlocal, especially when additional methods or attributes are needed.

🔍 Rule of Thumb

If you're debating global or nonlocal, ask whether a class or generator would better express the intent. They’re specialized tools—not substitutes for proper data modeling.


🟩 Final Thoughts

The global and nonlocal keywords are not conveniences—they are explicit mechanisms for controlling Python’s scoping and closure behavior. Understanding the python global vs nonlocal keyword distinction means understanding how Python binds names at compile time and manages variable lifetime through cell objects. Assignment in Python is not neutral—it defines scope. Without global or nonlocal, any assignment traps the name in the local scope, even if you intended to modify an outer binding. In modern Python, prefer immutability, clear interfaces, and encapsulated objects. Use nonlocal sparingly for lightweight functional patterns. Use global only when module-level state is intentional and documented. Most state management problems are better served by classes, generators, or context managers—but when you need a minimal, stateful closure, knowing how nonlocal works is essential.

❓ Frequently Asked Questions

Can I use both global and nonlocal in the same function?

Yes, but only for different variables. You can declare one name as global and another as nonlocal in the same function. Applying both to the same name is a logical contradiction and results in a SyntaxError. (Also read: 🐍 python pip vs pipenv vs poetry — which one should you actually use?)

Why do I get UnboundLocalError when I didn’t use global or nonlocal?

Because Python sees an assignment (like x = x + 1) and marks x as local to the function. Any read of x before the assignment then refers to a local variable that hasn’t been initialized. Use global or nonlocal to bind to an outer scope instead.

Does nonlocal work with nested classes or only functions?

No, nonlocal only applies to nested functions. Classes—even those defined inside functions—do not participate in the closure mechanism. Their scope is evaluated independently, and they cannot access enclosing function variables via nonlocal.

📚 References & Further Reading

  • Python scoping rules — official documentation on LEGB and namespace resolution: docs.python.org
  • Closures and free variables — how cell objects work in nested functions: docs.python.org
  • Global and nonlocal statements — syntax and semantics: docs.python.org