python-nested-import-nameerror

python-nested-import-nameerror is a skill for Claude Code, Codex from humanerd-drew/opencode-drewgent. It costs 30 tokens per session (1,472 once invoked), scanned A, original, MIT.

An explanation of a Python scoping bug caused by importing a module inside a function or nested function. Python then treats that name as local within the surrounding function, which can cause an error before the import runs.

In plain words
What is it for?
Diagnosing and preventing `UnboundLocalError` problems involving imports such as `json` inside nested Python code.
Why use it?
The error can look like a missing module even when the module is installed. Understanding Python’s local-variable rules points to the safer fix: import the module at file level.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one.

Good fit Diagnosing and preventing UnboundLocalError problems involving imports such as json inside nested Python code.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/humanerd-drew/opencode-drewgent/python-nested-import-nameerror
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add humanerd-drew/opencode-drewgent --skill python-nested-import-nameerror
Clone the repo
git clone --depth 1 https://github.com/humanerd-drew/opencode-drewgent

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for python-nested-import-nameerror

README.md
[![agentmods](https://agentmods.dev/badge/skills/humanerd-drew/opencode-drewgent/python-nested-import-nameerror.svg)](https://agentmods.dev/skills/humanerd-drew/opencode-drewgent/python-nested-import-nameerror)
Your own site
<a href="https://agentmods.dev/skills/humanerd-drew/opencode-drewgent/python-nested-import-nameerror"><img src="https://agentmods.dev/badge/skills/humanerd-drew/opencode-drewgent/python-nested-import-nameerror.svg" alt="Measured on agentmods" height="20"></a>
Per session 30 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 1,472 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00030 $0.01472
Opus 5 $0.00015 $0.00736
Sonnet 5 $0.00006 $0.00294
Haiku 4.5 $0.00003 $0.00147

Measured 4d ago against content hash 809923c9e3fe, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-07, from the pricing page.

Security

Grade A, and why

python-nested-import-nameerror scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/software-development/python-nested-import-nameerror/SKILL.md · 112 lines

How it starts

The opening of the file, as written. The whole thing — 112 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python Nested Import NameError Bug Pattern

Python 함수 내부에서 import json 또는 import json as X를 실행하면, 같은 함수 내 모든 json 참조가 local variable가 됨. 선언보다 앞에서 json.dumps() 등을 호출하면 → UnboundLocalError.

Root Cause — Python Lexical Scoping

Python 컴파일러가 함수 전체를 훑는다. 함수 어딘가에서 import json as X를 보면, 해당 함수 스코프의 json 이름을 local variable로 등록한다. 이후 json.dumps()가 호출되더라도, local json은 아직 값이 할당되지 않았으므로 → UnboundLocalError.

def run_conversation(self):
    # ...
    if isinstance(raw, dict):
        assistant_message.content = (
            raw.get("text", "")
            or raw.get("content", "")
            or json.dumps(raw)   # ❌ line 10646 — local `json` 아직 없음
        )
    # ...
    def inner():
        import json as _json_mod  # line 10929 — 이 한 줄이
        _json_mod.dumps(...)       # `json` 이름을 local로 만듦

# Error: cannot access local variable 'json' where it is not associated with a value

The Fix — module-level import 우선

import json  # file top — module-level (line 29)

def run_conversation(self):
    json.dumps(raw)  # ✅ module-level `json` 사용

Applied Fixes in run_agent.py

2026-05-30 fixrun_conversation() 내부 4곳 수정:

수정 전 수정 후 이유
10929 import json as _json_mod # json is module-level (line 29) 주석 처리 nested import 제거 — json 이름 local로 shadowing됨
10934 _json_mod.dumps(args) json.dumps(args) module-level json 직접 사용
10944 _json_mod.loads(args) json.loads(args) module-level json 직접 사용
11548 import os, json # os, json are module-level 주석 처리 nested import 제거

주의: 이전 수정(2026-05-29)에서 import json as _json_mod를 주석 처리하고 json.dumps() 사용으로 바꿨지만, 같은 함수 스코프 내의 json.loads() 호출은 여전히 _json_mod.loads()로 남아있음 → NameError: name '_json_mod' is not defined 발생

정답: 모든 nested import json 제거 → module-level import json (line 29) 하나만 사용

Detection Commands

# nested import json 패턴 찾기
grep -n "import json\|import os, json" ~/.{{AGENT_NAME_LOWER}}/source/{{AGENT_NAME_LOWER}}-agent/run_agent.py

# 함수 내부 import json AST로 정확히 찾기
python3 -c "
import ast, sys
with open(sys.argv[1]) as f:
    tree = ast.parse(f.read())
for node in ast.walk(tree):
    if isinstance(node, ast.FunctionDef):
        local = [n for n in ast.walk(node) if isinstance(n, (ast.Import, ast.ImportFrom)) and any(a.name == 'json' for a in n.names)]
        if local:
            print(f'{node.name}: line {local[0].lineno} — {ast.unparse(local[0])}')
" ~/.{{AGENT_NAME_LOWER}}/source/{{AGENT_NAME_LOWER}}-agent/run_agent.py

# _json_mod 잔여 확인
grep -n "_json_mod" ~/.{{AGENT_NAME_LOWER}}/source/{{AGENT_NAME_LOWER}}-agent/run_agent.py

Read the full file on GitHub · 112 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 112 lines · 30 tokens per session scan A 809923c9e3fe

Subscribe to this mod's changes

python-nested-import-nameerror is a skill published in the GitHub repository humanerd-drew/opencode-drewgent (2 stars, last pushed 1mo ago), licensed MIT. It adds 30 tokens to every session and 1,472 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.

Related

Other skills, from other repositories

python-code-quality

Code quality checks, linting, formatting, and type checking commands for the Agent Framework Python codebase. Use this when running checks, fixing lint errors, or troubleshooting CI failures.

microsoft/agent-framework · 40 tokens

plugin-architecture-patterns

Design, implement, or diagnose Xberg plugin traits, typed registries, priority collisions, lifecycle, native extractors, and Alef-generated Python plugin bridges. Load for plugin-system work, not ordinary extractor parsing.

xberg-io/xberg · 49 tokens

test-corpus

The testdocuments submodule is a bucket-fetched fixture corpus that is not committed. This skill covers readtestfixture, missing fixtures, valid A/B controls, and submodule push order. Load before running Rust tests on a fresh clone, setting up an A/B control, adding a fixture-backed test, or diagnosing…

xberg-io/xberg · 72 tokens

idapython

IDA Pro Python scripting for reverse engineering. Use when writing IDAPython scripts, analyzing binaries, working with IDA's API for disassembly, decompilation (Hex-Rays), type systems, cross-references, functions, segments, or any IDA database manipulation. Covers ida modules (50+), idautils iterators, and common…

mrexodia/ida-pro-mcp · 77 tokens

stack-trace-python-probe

Internal helper for meta-stack-trace-investigator. Use when a Python traceback needs Python-specific root-cause checks, pytest reproducer guidance, and defensive patch targets.

opensquilla/opensquilla · 40 tokens

python-debug-execution-911f17

Debug Python script execution failures by capturing full tracebacks and verifying working directory.

HKUDS/OpenSpace · 23 tokens