|
Download tasks/data/forward/adamchainz__patchy.eae591b/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 59 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adamchainz__patchy.eae591b/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adamchainz__patchy.eae591b/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adamchainz__patchy.eae591b/instruction.md
59 kB
| # adamchainz/patchy | |
| ## Project Overview | |
| Patchy is a small Python library for patching the inner source of Python functions at runtime. Rather than monkey patching a module-level attribute, Patchy applies a unified diff directly against a function's source code and replaces the function's code object, leaving the function object itself intact. This means all references to the patched function throughout a process see the new behavior, and the patch itself can include surrounding context lines that act as a guard against unexpected upstream changes. The library is particularly useful for applying small, temporary fixes to external libraries without maintaining a full fork, and it raises a ValueError when a patch no longer applies cleanly. | |
| The public API consolidates into a single top-level patchy module. The core patch() function takes either a function object or a dotted import path plus a diff, then retrieves the source with inspect.getsource(), dedents and applies the patch through the standard patch command-line utility, recompiles the resulting source, and swaps in the new code object. unpatch() reverses the operation, and temp_patch() provides context-manager and decorator forms for temporarily applying and removing a patch. replace() offers a simpler, subprocess-free alternative that compares an expected source via AST before substituting a fully specified replacement. An mc_patchface() alias provides the same functionality under a humorous name. Special handling for instancemethod, classmethod, and staticmethod wrappers ensures the underlying function is patched correctly. | |
| Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance. | |
| ## Submission Constraints (read carefully — the evaluation depends on these) | |
| This is a **closed-book** task. The graded test suite is **hidden** and will be | |
| injected into the workspace at evaluation time. To be scored correctly you MUST | |
| follow these rules: | |
| 1. **Do NOT create or modify any files under the test directories** (e.g. | |
| `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`). | |
| The grader injects its own test files at those paths; any file you place | |
| there will collide with the injected suite and cause the whole evaluation to | |
| score 0. Implement **only** the library/source code — never the tests. | |
| 2. **Your package MUST be importable by the name the tests use.** The hidden | |
| tests `import` your package by its documented top-level name (see the | |
| Project Directory Structure and API Usage Guide below). Provide a valid | |
| `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that | |
| `pip install -e .` succeeds and the package imports cleanly. If your package | |
| is not installable/importable, every test errors out and the reward is 0. | |
| 3. **Match the documented module paths and public API exactly** (names, | |
| signatures, and any literal error/exception strings). Internal helpers not | |
| listed in the API guide may be implemented however you like. | |
| ## Install / Reconstruction Contract | |
| Follow this contract before implementing the documented APIs: | |
| - **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`. | |
| - **Package/distribution name**: `patchy` | |
| - **Package roots**: `src` | |
| - **Install strategy**: `editable-install` | |
| - **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package. | |
| - **Provision commands**: | |
| ```bash | |
| python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' | |
| programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } | |
| export -f programgen_pip_install | |
| programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel | |
| programgen_pip_install python3 -m pip install 'uv-build>=0.12.1,<0.13' | |
| ( | |
| programgen_install_report="$(mktemp)" | |
| trap 'rm -f "$programgen_install_report"' EXIT | |
| SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" | |
| python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" | |
| ) | |
| ``` | |
| - **Runtime setup**: | |
| ```bash | |
| { | |
| [ -e "$PWD"/README.rst ] || { mkdir -p "$(dirname "$PWD"/README.rst)"; : > "$PWD"/README.rst; }; | |
| SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; | |
| } | |
| ``` | |
| - **Project root for installation**: `.` | |
| - **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0` | |
| - **Test directory**: `tests` | |
| - **Test command**: `bash -lc 'set -uo pipefail | |
| run=(python3 -m pytest -vv -o addopts= tests/test_cache.py tests/test_patch.py tests/test_patch_then_unpatch.py tests/test_replace.py tests/test_temp_patch.py tests/test_unpatch.py) | |
| if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_cache.py tests/test_patch.py tests/test_patch_then_unpatch.py tests/test_replace.py tests/test_temp_patch.py tests/test_unpatch.py); fi | |
| collect=(python3 -m pytest -q -o addopts= tests/test_cache.py tests/test_patch.py tests/test_patch_then_unpatch.py tests/test_replace.py tests/test_temp_patch.py tests/test_unpatch.py) | |
| collected_output=$("${collect[@]}" --collect-only) | |
| collect_rc=$? | |
| if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then | |
| printf "%s\n" "$collected_output" >&2 | |
| printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 | |
| exit "$collect_rc" | |
| fi | |
| mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') | |
| if [ "${#collected[@]}" -gt 500 ]; then | |
| while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') | |
| fi | |
| "${run[@]}"; exit $?'` | |
| - **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately. | |
| ## Environment & Project Structure | |
| - **Language**: python | |
| - **Build system**: python | |
| - **Test command**: `bash -lc set -uo pipefail | |
| run=(python3 -m pytest -vv -o addopts= tests/test_cache.py tests/test_patch.py tests/test_patch_then_unpatch.py tests/test_replace.py tests/test_temp_patch.py tests/test_unpatch.py) | |
| if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_cache.py tests/test_patch.py tests/test_patch_then_unpatch.py tests/test_replace.py tests/test_temp_patch.py tests/test_unpatch.py); fi | |
| collect=(python3 -m pytest -q -o addopts= tests/test_cache.py tests/test_patch.py tests/test_patch_then_unpatch.py tests/test_replace.py tests/test_temp_patch.py tests/test_unpatch.py) | |
| collected_output=$("${collect[@]}" --collect-only) | |
| collect_rc=$? | |
| if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then | |
| printf "%s\n" "$collected_output" >&2 | |
| printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 | |
| exit "$collect_rc" | |
| fi | |
| mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') | |
| if [ "${#collected[@]}" -gt 500 ]; then | |
| while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') | |
| fi | |
| "${run[@]}"; exit $?` | |
| ### Project Directory Structure | |
| ``` | |
| .editorconfig | |
| .github/CODE_OF_CONDUCT.md | |
| .github/FUNDING.yml | |
| .github/ISSUE_TEMPLATE/config.yml | |
| .github/ISSUE_TEMPLATE/feature-request.yml | |
| .github/ISSUE_TEMPLATE/issue.yml | |
| .github/SECURITY.md | |
| .github/workflows/main.yml | |
| .gitignore | |
| .pre-commit-config.yaml | |
| .typos.toml | |
| CHANGELOG.rst | |
| HISTORY.rst | |
| LICENSE | |
| README.rst | |
| pirate.png | |
| pyproject.toml | |
| src/patchy/__init__.py | |
| src/patchy/api.py | |
| src/patchy/cache.py | |
| src/patchy/py.typed | |
| tox.ini | |
| uv.lock | |
| ``` | |
| ## API Usage Guide | |
| Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely. | |
| ### Capability: Runtime function source patching | |
| # Runtime function source patching with `patchy` | |
| ## Purpose | |
| `patchy.patch` edits the source text of an existing, live Python function and swaps in a recompiled code object. The function object stays in place; only `__code__` changes. Because no name is rebound, every reference in the process (a local, a module attribute, a class attribute, or an imported alias) immediately observes the new behavior. The patch is a unified diff, so hunks can include surrounding context lines that act as a guard against stale upstream source; when the source no longer matches, patching fails loudly with a `ValueError`. | |
| ## Component relationships | |
| - `patch(...)` is the forward entry point and delegates all work to an internal helper with `forwards=True`. | |
| - `mc_patchface` is an alias of the same function. | |
| - `unpatch(...)` runs the same helper with `forwards=False`, applying the patch text in reverse. | |
| - `temp_patch` remembers a target and patch text, calls `patch` on entry and `unpatch` on exit, and offers a decorator form. | |
| - `replace(...)` is a separate, subprocess-free path: it may assert an expected source via AST equality, then directly substitutes a fully specified replacement source. | |
| - `_patching_cache` is a process-wide cache that makes repeated patching and reversal fast and repeatable. | |
| - `_get_source` and `_get_real_func` resolve the current source text and the underlying function to mutate. | |
| - `_set_source` recompiles and swaps the code object while preserving `__future__` flags, free variables, and name mangling. | |
| ## Forward workflow | |
| 1. A string target is resolved to a function with `pkgutil.resolve_name` using an absolute dotted path such as `pkg.mod.Class.method`. | |
| 2. Current source is read from the weak-keyed source map first; only on a miss is `inspect.getsource` used, followed by `textwrap.dedent`. | |
| 3. The patch text is dedented to the same baseline. | |
| 4. The patch is first looked up in the cache keyed by `(source, patch_text, forwards)`. A hit returns the stored result without running the `patch` executable. | |
| 5. On a miss, a temporary directory is created. The current source is written to a file named `{func.__name__}.py` and the patch to `{func.__name__}.patch`. If the patch text does not already end with a newline, one is appended to the patch file; this is what lets a diff whose final line lacks a newline still apply. | |
| 6. The system `patch` runs as `patch --force source.py source.patch`, or `patch --force --reverse source.py source.patch` for unpatch, with stdout and stderr captured as text. | |
| 7. A non-zero exit raises a `ValueError`. The GNU-patch message starts with `Could not apply the patch to '<name>'.` (reverse uses unapply/from). The diagnostic appends the captured `patch` stdout/stderr, then the source that failed, then the patch text. BSD patch output differs but is carried in the same exception. | |
| 8. On success the patched file is read back as the new source and the temporary directory is removed in a `finally` block. Only after that cleanup is the cache populated with the new source. | |
| ## Compilation and code swap | |
| `_set_source` performs the source-to-bytecode conversion without rebinding the function: | |
| - The real function is peeled with `inspect.ismethod`; a bound method exposes its `__func__`, so classmethods, staticmethods, and instance access all patch the shared underlying function. | |
| - The original `__code__.co_flags` are masked with the union of every `__future__.all_feature_names` compiler flag and reused when compiling, so a patched function keeps behavior such as `from __future__ import annotations`. | |
| - The class name is inferred from `__qualname__`; a trailing `<locals>` segment means no class context. | |
| - Free variables are the delicate part: the new code object must use exactly the original `co_freevars`. The helper wraps the patched definition in a factory named `__patchy_freevars__`, binds every original free-variable name to `object()` in that factory, and appends bare reference statements to the patched body. This forces a patch that drops a free variable to still compile against the same name slots in the same order. | |
| - For methods, the patched definition is wrapped in a synthetic class with the original class name. That makes private-name mangling compile identically, so `__mangled_name` becomes the same `_ClassName__mangled_name` the original used. A `global ClassName` statement is emitted when the class name is not itself a free variable (module-level classes); closure-nested classes skip the global. | |
| - For plain functions, the same factory wrapper is used with `global name` when the function name is not already a free variable. This keeps a module-level recursive function resolving its own name through globals after the swap, while a closure-resident function name stays a free-variable binding. | |
| - The wrapper is compiled with the filename `<patchy>` in `exec` mode, executed against a copy of the function's globals plus a fresh locals namespace, and the patched function object is obtained by calling `__patchy_freevars__`. | |
| - Only `real_func.__code__` is assigned from that new object. `__globals__`, `__name__`, `__qualname__`, `__defaults__`, and `__kwdefaults__` all remain attached to the original function object. | |
| - The patched source text is stored in the weak-keyed source map keyed by the real function. Therefore subsequent patches see the previously patched source, and `inspect.getsource` is not consulted again for that function. | |
| A test-sensitive consequence is default preservation: a function with a mutable default keeps the original default object and its accumulated state because only the code object is replaced. The default expression in the patched source is compiled inside the wrapper but its resulting object is discarded. | |
| ## Failure behavior and ordering | |
| - A failed patch is atomic: source is only read and modified inside the temporary directory, and `__code__` is assigned only after a successful patch. | |
| - The cache is populated only after the `patch` command succeeds. | |
| - Patches apply in sequence. A second patch must match the source produced by the first, because the source map is consulted before `inspect.getsource`. | |
| - A failed multi-hunk application reports which hunk failed and leaves the original behavior observable. | |
| - Reverse application also uses the cache. Since a successful forward patch stores both directions, unpatching a just-patched function normally returns the original source without invoking `patch` again. | |
| ## `temp_patch` | |
| `temp_patch(func, patch_text)` stores its arguments. `__enter__` calls `patch`; `__exit__` calls `unpatch` and returns `None`, so exceptions inside the block are never swallowed. The decorator form wraps the decorated function with `functools.wraps`, invokes it inside the context, and returns `None` from the wrapper instead of forwarding the decorated function's return value. | |
| ## Test-sensitive edge cases | |
| - Patching a function, an instance method, a classmethod, or a staticmethod all resolves to the same underlying function object. Diff hunks must reflect the form returned by `inspect.getsource`; decorated targets may include the decorator lines. | |
| - Recursive module-level functions are kept working by the `global function_name` pass; recursive closure functions are kept working by the free-variable wrapper. | |
| - Methods that use `super()` or private mangling are recompiled inside the synthetic class so both remain resolvable. | |
| - The runtime flag mask is built from `__future__.all_feature_names` compiler flags, and the original function's future flags are masked in and reused when compiling patched source. | |
| - The cache object has a `maxsize` of 100. When a store would exceed it, a random sample (at least two entries, roughly a quarter) is evicted rather than using an LRU order. | |
| #### Exact API Reference | |
| #### `patchy.api.patch` | |
| - **Import Path**: `from patchy.api import patch` | |
| - **Required Test Import Paths**: | |
| - patchy.patch | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Signature**: | |
| ```python | |
| def patch(func: Callable[..., Any] | str, patch_text: str) -> None | |
| ``` | |
| #### `patchy.api.temp_patch` | |
| - **Import Path**: `from patchy.api import temp_patch` | |
| - **Required Test Import Paths**: | |
| - patchy.temp_patch | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Kind**: class | |
| - **Signature**: | |
| ```python | |
| class temp_patch: | |
| def __init__(self, func: Callable[..., Any] | str, patch_text: str) -> None | |
| def __enter__(self) -> None | |
| def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> None | |
| def __call__(self, decorable: AnyFunc) -> AnyFunc | |
| func: Any | |
| patch_text: Any | |
| ``` | |
| #### `patchy.api._patching_cache` | |
| - **Import Path**: `from patchy.api import _patching_cache` | |
| - **Required Test Import Paths**: | |
| - patchy.api._patching_cache | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Kind**: constant | |
| - **Signature**: | |
| ```python | |
| _patching_cache: Any | |
| ``` | |
| - **Behavior**: Module-level value required by the test import contract. | |
| #### `patchy.api.mc_patchface` | |
| - **Import Path**: `from patchy.api import mc_patchface` | |
| - **Required Test Import Paths**: | |
| - patchy.mc_patchface | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Kind**: constant | |
| - **Signature**: | |
| ```python | |
| mc_patchface: Any | |
| ``` | |
| - **Behavior**: Module-level value required by the test import contract. | |
| ### Capability: Validated source replacement | |
| # Validated source replacement | |
| ## Purpose and relationship to the rest of patchy | |
| `replace` is the subprocess-free alternative to the diff-based `patch`. Instead of taking a unified diff and invoking the external `patch` command, `replace` takes a complete new function source, compiles it directly, and swaps the resulting code object onto the existing function object. It exists for callers who already know exactly what the replacement function should be and do not need line-level context hunks. Because it never shells out and never touches the diff cache, `replace` is unaffected by `patch` availability on the host. | |
| The optional expected-source guard makes this a *validated* replacement: before mutating anything, the capability can assert that the function's current source is structurally identical to a source the caller anticipates. This is the mechanism's guard against silently overwriting an upstream function that has drifted. If the assertion fails, the function is left untouched and the operation stops before compilation or code-object swap. | |
| ## How the pieces fit together in a realistic workflow | |
| A typical call passes the function object, an expected source literal, and a new source literal. With an expected source present, three phases run in strict order: | |
| 1. The expected source is dedented. | |
| 2. The function's current source is retrieved. | |
| 3. The two sources are parsed to ASTs and compared by structural dump. Only if they are equal does installation continue. | |
| Installation then dedents the new source, compiles it, and swaps `__code__` on the real underlying function. A mismatch in phase three raises `ValueError` before any state is changed, so a failed replacement has no residual effect on the function or the in-memory source record. | |
| After a successful replacement, the new source is recorded in an in-memory source record, a weak-key mapping keyed by the real function object. This recording is crucial for repeated replacement: a second call with an expected source is validated against the *most recently installed* source, not against the original source from disk. The tests exercise exactly this `replace`-twice workflow, where each subsequent expected source describes the previous replacement output. | |
| ## Source retrieval and method unwrapping | |
| The current source is obtained by first peeling wrapper forms off the callable to reach the underlying function object, then checking the in-memory source record for a stored replacement. Only when no stored source exists does the capability fall back to `inspect.getsource` and dedent the result. That means: | |
| - A function that has never been patched is read from its defining file. | |
| - A function previously changed by `patch`, `temp_patch`, or an earlier `replace` is validated against the synthetic source held in the in-memory source record, even if the file still says something different. | |
| Bound methods are unwrapped through `__func__`, so calling with `Artist.method` or `Artist().method` targets the same underlying function; all existing and future instances observe the change. | |
| ## Installation details and state changes | |
| The installation step intentionally changes only the code object. It does not rebuild, rewrap, or reassign the function object itself, so every reference to that function object throughout the process keeps working and sees the new body. The original values of `__defaults__`, `__kwdefaults__`, `__dict__`, `__globals__`, `__name__`, and `__qualname__` are preserved. This has a deliberately observable consequence for mutable defaults: accumulated state in a default argument survives replacement. The test suite verifies that a list default keeps its contents across a replacement even though the new code body differs. | |
| Compilation does not blindly call `compile` with default flags. It extracts the future feature flags from the original code object's `co_flags` (masked to the `__future__` feature bits) and passes them with `dont_inherit=True`. This preserves features such as postponed annotations so a function that only exists because of `from __future__ import annotations` still compiles under the same rules as before. | |
| Closure variables are handled by wrapping the replacement source in a synthetic wrapper function. The wrapper binds every original free variable name and appends force-use statements to the replacement body so the freshly compiled code object has exactly the same `co_freevars` as the original. If the new source dropped a closure reference, the appended statements keep the code object's free-variable tuple stable. | |
| Methods defined inside a class get one more layer: the replacement is parsed inside a synthesized class carrying the original class name so double-underscore identifier mangling resolves the same way it did in the original definition. This matters when a replacement references a `__private` style attribute. | |
| For ordinary functions, the wrapper returns the function under the original function name. The replacement source is therefore expected to define the function under the same name as the original; the library uses that name to retrieve the compiled result and install its code object. | |
| ## Ordering, defaults, and edge cases | |
| - `expected_source` of `None` skips validation entirely and installs the new source unconditionally. This is the documented no-guard form. | |
| - When validation is enabled, both sources are dedented before comparison, so large indented triple-quoted literals work naturally in tests. | |
| - Comparison is AST-based, not text-based. Whitespace, line breaks, blank lines, and comments are irrelevant; only the parsed structure matters. Tests demonstrate that a single-line expected source matches a multi-line original with identical AST structure. | |
| - The expected check happens before dedenting or compiling the new source, so malformed new source combined with a failing guard still reports the guard failure rather than a compile error. | |
| - A successful second replacement must supply the previously installed source as its expected source, since the in-memory source record shadows the on-disk definition. | |
| - The capability returns no value; the effect is entirely the code-object swap and the in-memory source record update. | |
| ## Non-obvious, test-sensitive behavior | |
| - The mismatch error is the primary guard failure mode and is tested by asserting the function was unchanged and that the message includes both the actual current source text and the expected source text. The message states that the code has changed from expected before printing each source block. | |
| - Formatting-only changes to either source do not trigger the guard. | |
| - Because validation reads through the in-memory source record, a previously patched function cannot be validated against its original file text; the expected source must reflect the current in-memory source. | |
| - The mutable-default test is sensitive to preservation of `__defaults__`: re-implementations that rebuild a function object or reset defaults will fail it. Only `__code__` should be reassigned. | |
| - Instance-method coverage is sensitive to unwrapping: stripping `__func__` must happen both for source lookup and for the final code-object assignment, or replacing a bound method will not affect the class. | |
| #### Exact API Reference | |
| #### `patchy.api.replace` | |
| - **Import Path**: `from patchy.api import replace` | |
| - **Required Test Import Paths**: | |
| - patchy.replace | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Signature**: | |
| ```python | |
| def replace(func: Callable[..., Any], expected_source: str | None, new_source: str) -> None | |
| ``` | |
| ### Capability: Patch result caching | |
| ## Patch result caching | |
| The patching flow always funnels through `_apply_patch(source, patch_text, forwards, name)`. Without a cache, every call to `patch()` or `unpatch()` would have to shell out to the system `patch` command, even when the exact same transformation has already been computed. Patch result caching removes that repeated subprocess cost by remembering, in process memory, the result of applying (or unapplying) a specific patch text to a specific source string. | |
| ### Components and how they fit together | |
| The cache is a single process-global `PatchingCache` instance named `_patching_cache` in `patchy.api`. It is created with `maxsize=100`. The `PatchingCache` class itself lives in `patchy.cache` and is importable as `patchy.cache.PatchingCache`. The public entry points `patch()` and `unpatch()` are thin wrappers around `_do_patch(func, patch_text, forwards=True/False)`. `_do_patch` resolves a dotted string path to a callable if necessary, obtains the current source via `_get_source()`, dedents the caller's `patch_text`, and calls `_apply_patch`. That one function is the only place the cache is consulted and populated. | |
| `_apply_patch` performs this sequence: | |
| 1. Try `_patching_cache.retrieve(source, patch_text, forwards)`. On a miss, the cache raises `KeyError`, and the function proceeds to the subprocess path. | |
| 2. On a miss, it creates a temporary directory, writes two files from the already-dedented `source` and already-dedented `patch_text`, appends a trailing newline to the patch file only if the dedented patch text does not end with one, invokes the `patch` command (`--force`, plus `--reverse` when `forwards` is `False`), and raises a `ValueError` if the return code is nonzero. | |
| 3. On success, it reads the patched file back as `new_source`, removes the temporary directory in a `finally` block, and only then calls `_patching_cache.store(source, patch_text, forwards, new_source)`. | |
| 4. It returns `new_source`. | |
| Failures never populate the cache because `store` is reached only after a successful `patch` return code. This matters for consistency: a bad or inapplicable patch keeps raising the full `patch`-derived error message on every attempt instead of silently returning a cached bad state. | |
| ### The cache key | |
| Entries are keyed by the tuple `(source, patch_text, forwards)`. All three parts are meaningful: | |
| - `source` is the dedented source string returned by `_get_source`. For an unpatched function this comes from `inspect.getsource()` and is then dedented; for a previously replaced function it comes from `_source_map`. Two identical source strings therefore hit the same cache entry regardless of which function object they came from. | |
| - `patch_text` is the dedented patch text after `_do_patch` has called `dedent` on the caller's argument. Callers who write the same patch with different leading indentation still share cache entries because the key is computed after dedenting. | |
| - `forwards` is a boolean direction flag. Applying and reversing are distinct operations and cannot share one entry. | |
| Because the key is `(source, patch_text, forwards)`, a cache hit happens only when the current source, the effective patch text, and the direction all match a previously successful operation. A changed upstream source automatically becomes a cache miss, which is what forces the real `patch` command to run and surface a `ValueError` when the context lines no longer line up. | |
| ### Bidirectional storage | |
| `PatchingCache.store()` deliberately writes two entries for every one operation: | |
| - `_cache[(source, patch_text, forwards)] = new_source` | |
| - `_cache[(new_source, patch_text, not forwards)] = source` | |
| This makes a later reversal cheap. After `patch(f, p)` succeeds, the entry `(original, p, True) -> patched` is stored together with `(patched, p, False) -> original`. A subsequent `unpatch(f, p)` therefore hits the cache immediately: its key is `(patched, p, False)`, exactly the reverse entry that was installed for free. Likewise, after `unpatch(f, p)` succeeds when no prior cache entry exists, store installs `(patched, p, False) -> original` and `(original, p, True) -> patched`, so a subsequent re-`patch` is also a hit. In effect, once any pair of source states has been connected by a successful operation, both directions become cache-resident together. | |
| ### Boundedness and eviction | |
| The cache never grows without bound. Before inserting, `store` checks `if len(self._cache) + 2 > self.maxsize`. The `+ 2` accounts for the fact that every store adds two entries (forward and reverse). When the threshold is crossed, it evicts `max(2, len(self._cache) // 4)` randomly chosen keys, then inserts the two new entries. With the process default `maxsize=100`, the dictionary size stays at or below 100 after each store. | |
| Eviction is intentionally random (via `random.sample`). Do not write tests that depend on any particular victim surviving or being dropped. Tests should instead reason about observable behavior: hits happen or miss, but the cache is an internal speed optimization and its precise fill state is not part of the public contract. Reconstructing the implementation should preserve the randomized eviction policy and the "at least 2, else 25%" deletion rule, including the order of operations: the eviction check happens before anything is inserted, so the two fresh entries are never immediately deleted by the same store call. | |
| ### Non-obvious edge cases and test-sensitive behavior | |
| - **Miss raises `KeyError`.** `retrieve` does not return an optional sentinel; it performs a plain dict lookup. `_apply_patch` relies on catching that `KeyError`. Any re-implementation of the cache that returns `None` on miss would change `_apply_patch` behavior unless the caller's `try/except KeyError` is also updated. With the original pattern, a cached value of `None` is impossible anyway because stored values are always source strings. | |
| - **Cache keys use post-dedent text.** `_do_patch` dedents `patch_text` before calling `_apply_patch`, and `_get_source` returns dedented source. The cache therefore compares normalized text, not the raw function header indentation or raw diff indentation. | |
| - **Trailing newline normalization is not part of the key.** The subprocess path writes a trailing newline to the patch file when missing, but the key is the dedented `patch_text` as provided (before that file-writing normalization). A cache hit returns the previously stored `new_source` and skips patch-file normalization entirely. | |
| - **The reverse entry stores the exact opposite mapping.** Store does not run `patch --reverse` or otherwise derive the reverse result; it records the known `source` and `new_source` pair under flipped direction. A reverse operation that starts from some third source state will miss and run the real reverse patch. | |
| - **Cache is process-global and lives for the interpreter lifetime.** `_patching_cache` is a module-level singleton; `clear()` resets only the dictionary, not `maxsize`. There is no automatic eviction by age or weak references, and entries can reference function names only indirectly through source strings, so cleared or reused functions are no concern. | |
| - **Retrieval happens before any temporary file or subprocess work.** A full cache hit does not create a temporary directory, does not touch the filesystem, and does not run `patch`. This is the entire performance benefit. | |
| - **Storage happens after the temporary directory is removed.** If `shutil.rmtree` or reading the patched file failed, `store` would not run; in normal operation, only successful patch outcomes are cached. | |
| - **The cache does not call `_set_source` or mutate functions.** `_apply_patch` only returns the new source string. `_do_patch` then passes it to `_set_source`, which compiles and swaps the code object. Caching is independent of code-object swapping; a cache hit simply returns the same string that would otherwise have been produced by `patch`, and `_set_source` still runs on every call. | |
| - **Extremely small `maxsize` values (< 2) are pathological.** With `maxsize=0` or `1`, the eviction computation `max(2, len // 4)` can demand more keys than exist, causing `random.sample` to raise. The shipped default of 100 never hits this, but a re-implementation should either document the constraint or match this behavior. | |
| - **Threading is not addressed.** The dict is plain and eviction is non-atomic. Concurrent patch operations from multiple threads can interleave check-then-insert sequences; this matches the original library's behavior, so re-implementations need not add locking to pass the original tests unless the surrounding application demands it. | |
| ### How the pieces appear in a realistic workflow | |
| A typical cycle is `temp_patch` entering and exiting a block. On entry, `patch` resolves the function, dedents the patch, computes a key such as `(original_source, normalized_patch, True)`, and misses. It shells out once, stores both direction entries, and swaps the code object. On exit, `unpatch` computes `(patched_source, normalized_patch, False)`, hits the reverse entry installed during `patch`, and immediately returns the original source. The second `_set_source` still compiles and reassigns the code object, but no `patch` subprocess runs. If the same temporary patch is applied and removed many times, only the very first application and any later cache eviction require subprocess work. If, between uses, the underlying function's source changes, the key changes and the cache safely misses, letting the `patch` command re-evaluate the diff against the new reality. | |
| Because the cache is keyed by source text and not by function identity, it is also correct for multiple distinct function objects that happen to share byte-for-byte identical dedented source. They share cached patch results. The optimization is pure memoization of a deterministic function from `(source, patch_text, forwards)` to `new_source`, so sharing is safe. | |
| #### Exact API Reference | |
| #### `patchy.api.unpatch` | |
| - **Import Path**: `from patchy.api import unpatch` | |
| - **Required Test Import Paths**: | |
| - patchy.unpatch | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Signature**: | |
| ```python | |
| def unpatch(func: Callable[..., Any] | str, patch_text: str) -> None | |
| ``` | |
| #### `patchy.cache.PatchingCache` | |
| - **Import Path**: `from patchy.cache import PatchingCache` | |
| - **Required Test Import Paths**: | |
| - patchy.cache.PatchingCache | |
| - **Exact Test Import Statements**: | |
| - from patchy.cache import PatchingCache | |
| - **Kind**: class | |
| - **Signature**: | |
| ```python | |
| class PatchingCache: | |
| def __init__(self, maxsize: int) -> None | |
| def clear(self) -> None | |
| def retrieve(self, source: str, patch_text: str, forwards: bool) -> str | |
| def store(self, source: str, patch_text: str, forwards: bool, new_source: str) -> None | |
| maxsize: Any | |
| _cache: dict[tuple[str, str, bool], str] | |
| ``` | |
| ### Capability: Additional components | |
| # patchy.api module | |
| ## Capability purpose | |
| The remaining documented component is the `patchy.api` module itself. It is the implementation home for every public callable in the library and is exercised by tests even when the tests nominally import the top-level `patchy` package. The module must import cleanly for `import patchy.api` and must remain the single place where the public behavior is defined; the top-level package simply re-exports it. | |
| ## Relationship to the top-level package | |
| `patchy/__init__.py` contains only: | |
| ```python | |
| from .api import * # noqa | |
| ``` | |
| The star import is controlled by `patchy.api.__all__`, which lists exactly `("patch", "mc_patchface", "unpatch", "replace", "temp_patch")`. Consequently `patchy.api` is authoritative: any function that is re-exportable through the package must be listed in `__all__`, and any alias that should be public must be assigned in `api.py` (the `mc_patchface = patch` alias is created there rather than in the package). A test that does `import patchy.api` and then uses `patchy.api.patch` exercises the same object that a test doing `from patchy import patch` receives; the two must be the same callable object and must share the same module-level state. | |
| ## Import-time state and side effects | |
| Importing the module performs real setup but no patching. The import: | |
| - pulls in `ast`, `inspect`, `os`, `shutil`, `subprocess`, `tempfile`, `types`, `textwrap`, `weakref`, `functools`, `collections.abc` and `typing` helpers; | |
| - imports `PatchingCache` from the sibling `.cache` module; | |
| - imports `__future__` inside a `if True:` block and imports `pkgutil.resolve_name` under the alias `pkgutil_resolve_name`; | |
| - defines the public callables (`patch`, `mc_patchface`, `unpatch`, `replace`, and the `temp_patch` class) and the private helpers they rely on, including `_do_patch`; | |
| - creates the module-level `_patching_cache = PatchingCache(maxsize=100)`; | |
| - defines `_get_flags_mask` and assigns `FEATURE_MASK` by OR-ing the `compiler_flag` of every name in `__future__.all_feature_names`; | |
| - creates the module-level weak-key `_source_map = WeakKeyDictionary()`. | |
| Those module globals are shared state for all operations in a process. `_patching_cache` is what the previously documented `PatchingCache` component is attached to: it has capacity 100 and is populated whenever a patch is applied in either direction through `_apply_patch`, which is reached by `patch`/`unpatch`/`temp_patch` (not by `replace`). `_source_map` maps a patched function's underlying function object to its currently active source string so that a second patch of the same function finds the previously modified source rather than `inspect.getsource()`'s original file text. Both must be created at import time, not lazily: `_get_source` and `_set_source` (used by `patch`, `unpatch`, and `replace`) reference `_source_map` directly, while `_apply_patch` (used by `patch`, `unpatch`, and `temp_patch`) references `_patching_cache` directly. | |
| ## How the module participates in workflows | |
| 1. A caller imports `patchy` (or `patchy.api`). Import keys off the module-level setup above. | |
| 2. A call such as `patch("some.module.func", diff)` passes the string to the internal `_do_patch`, which performs `pkgutil_resolve_name` only when `func` is a `str`; `unpatch` does the same. The module-level helpers in `api.py` are the only place that retrieval, dedenting, patch invocation, compilation, and code-object swapping occur. | |
| 3. `replace` and `temp_patch` live in the same module and therefore observe the same `_source_map`; `temp_patch` reaches `_patching_cache` through the module's `patch` and `unpatch`. A `temp_patch` context calls the module's `patch` and `unpatch`, so cache entries produced inside the context are plain cache entries with no separate context stack. | |
| 4. Tests that exercise `patchy.api` directly (as opposed to `patchy`) still receive the module globals described above, including the same cache object. Clearing behavior, capacity, and the weak-key source map do not differ between import styles. | |
| ## Import-path and packaging constraints | |
| The deterministically verified source file is `src/patchy/api.py`, so the module's runtime dotted path is `patchy.api` under the project's source layout. For re-implementation to pass collection, both `import patchy` and `import patchy.api` must succeed; there is no separate fake module at the package root and no `__init__`-level redefinition of the public functions. The `py.typed` marker is adjacent to the package but does not affect import behavior. | |
| ## Ordering and defaults that matter | |
| - `__all__` ordering is `patch`, `mc_patchface`, `unpatch`, `replace`, `temp_patch`. The order does not change behavior but reflects the defined sequence of the public API. | |
| - `_patching_cache` is constructed with `maxsize=100` before any public call can run. | |
| - `FEATURE_MASK` is computed eagerly. This is important because later recompilation of patched source inspects the original function's `co_flags` under this mask to preserve future-import behavior. | |
| - Name resolution of dotted paths is performed inside `_do_patch` only when `func` is a `str`; `patch` and `unpatch` do not resolve before dispatch, and importing `api.py` never resolves anything. | |
| - The `patch` command-line executable is not invoked at import time. A missing `patch` binary therefore makes the library import fine but makes patch application fail later. | |
| ## Edge cases and test-sensitive behavior | |
| - `import patchy.api` must not emit output, create temp directories, or touch the filesystem beyond normal Python module import. | |
| - The module uses a conditional `if True: import __future__`. Re-implementations should keep an unconditional `import __future__` or equivalent; the point is only that the future-feature compiler flags are available to compute `FEATURE_MASK`. | |
| - Because `_source_map` is keyed weakly, only functions that are still referenced elsewhere keep their modified sources. This is intentional: keeping strong references would leak patched functions after the caller drops them. | |
| - The module sets `from __future__ import annotations`, so all annotation strings are lazy. A re-implementation that omits this can break on older Python versions where `Callable[..., Any] | str` is not valid at runtime import. | |
| - The top-level package must not define a competing `__all__`; tests can import `patchy.api.__all__` and expect it to contain exactly the five public names. If `__init__` adds extra attributes they are not part of this capability. | |
| - Hidden-test collection that imports `patchy.api` directly relies on the fact that no patching primitive is decorated or wrapped in a way that would make `__all__` names differ from the objects obtained by `from patchy import ...`. | |
| To re-implement this capability faithfully, keep every public entry point in `patchy/api.py`, re-export it through the package `__init__` with a star import governed by `__all__`, and preserve the import-time construction of `FEATURE_MASK`, `_source_map`, and `_patching_cache`. | |
| #### Exact API Reference | |
| #### `patchy.api` | |
| - **Import Path**: `from patchy import api` | |
| - **Required Test Import Paths**: | |
| - patchy.api | |
| - **Exact Test Import Statements**: | |
| - import patchy.api | |
| - **Kind**: module | |
| - **Behavior**: Module required during hidden-test collection. | |
| ## Detailed Implementation Nodes | |
| ### Node: Runtime function source patching | |
| # Implementation nodes | |
| ## Functional constraints | |
| - Source acquisition: after the first successful patch, always read modified source from the weak-keyed source map keyed by the real function; otherwise use `inspect.getsource` and `textwrap.dedent`. Dedent the patch text too. | |
| - String targets: resolve with `pkgutil.resolve_name` before patching. | |
| - Real function: if `inspect.ismethod(target)`, mutate `target.__func__`; otherwise mutate the target itself. Assign the new code object only to that real function. | |
| - `replace`: when `expected_source` is not `None`, dedent it and compare it against the current source by AST equality, raising `ValueError` on mismatch; then dedent `new_source` and call `_set_source` directly. It must not invoke the external `patch` executable or the patch cache, but `_set_source` still updates the weak source map. | |
| - Environment: call the external `patch` executable from `PATH` with `--force` always and `--reverse` only when moving backwards; capture stdout/stderr as text. | |
| - Newline normalization: append `\n` to the patch file contents when the patch text does not already end with `\n`. | |
| - Cache: key exactly `(source, patch_text, forwards)`. A forward hit returns the new source; a reverse hit returns the original. Store both directions after a successful subprocess patch. Cap capacity at 100 and evict a random sample of at least two entries when needed. | |
| - Compilation: compile with `filename="<patchy>"`, mode `"exec"`, `dont_inherit=True`, and flags equal to the original `co_flags & FEATURE_MASK` plus any AST-only flag needed for parsing. | |
| - Free variables: build a wrapper that binds every original `co_freevars` name to a fresh `object()` and forces its use in the patched body so the compiled code uses identical free-variable slots in the same order. | |
| - Wrapping: use a factory named `__patchy_freevars__`. For methods, emit a class with the original class name, insert the patched definition as a method body, and return `ClassName.method`; for functions, return the patched function by name. Emit `global` only when that name is not already a free variable. | |
| - Swap: assign `real_func.__code__ = returned_patched_func.__code__`; do not mutate other function attributes. Store the patched source in the weak source map. | |
| - Direction: implement forward and reverse through one helper that flips a `forwards` flag. A non-zero `patch` exit must raise `ValueError` containing captured output, the failing source, and the failing patch text. | |
| - `temp_patch`: `__enter__` applies, `__exit__` unapplies and returns `None`; `__call__` preserves metadata with `functools.wraps` and runs the wrapped function inside the context. | |
| ## Usage example | |
| ```python | |
| import patchy | |
| def sample() -> int: | |
| return 1 | |
| patchy.patch( | |
| sample, | |
| """\ | |
| @@ -1,2 +1,2 @@ | |
| def sample() -> int: | |
| - return 1 | |
| + return 9001 | |
| """, | |
| ) | |
| assert sample() == 9001 | |
| ``` | |
| ### Node: Validated source replacement | |
| # Implementation constraints | |
| - Accept a callable object and two source strings; do not accept a dotted import path here. Return nothing. | |
| - If an expected source is given, dedent it first, fetch the current source, parse both with `ast.parse`, and compare `ast.dump` outputs. Raise `ValueError` before any mutation when the dumps differ and include the current and expected source text in the message. | |
| - If no expected source is given, skip validation and proceed straight to installation. | |
| - Dedent the new source before compiling it. | |
| - Retrieve the current source from a weak-key source map keyed by the real (unwrapped) function before falling back to `inspect.getsource` plus dedent; always record the installed source back into that map. | |
| - Unwrap bound methods via `__func__`; inspect methods directly, not the class, so the same underlying function is found and modified. | |
| - Compile the replacement with the original code object's `__future__` feature flags and `dont_inherit=True`; preserve annotations features. | |
| - Preserve the original free-variable tuple by wrapping the replacement and force-using every original `co_freevars` name. | |
| - For methods, synthesize a class with the original class name so name mangling matches. | |
| - Assign only `real_func.__code__` to the new code object. Do not replace the function object, its defaults, globals, name, qualname, or dict. | |
| - The replacement source should define the function under the same name as the original so the synthesized wrapper can return and install it. | |
| ## Usage example | |
| ```python | |
| import patchy | |
| def sample() -> int: | |
| return 1 | |
| patchy.replace( | |
| sample, | |
| 'def sample() -> int: return 1', | |
| 'def sample() -> int: return 42', | |
| ) | |
| assert sample() == 42 | |
| ``` | |
| ### Node: Patch result caching | |
| ## Implementation constraints | |
| - Maintain a plain dictionary keyed by `(source, patch_text, forwards)`, where all three are strings or booleans and the stored value is a source string. | |
| - A miss must raise `KeyError` from the lookup itself; the caller treats `KeyError` as the miss signal. | |
| - `store` inserts two entries atomically in concept: `(source, patch_text, forwards) -> new_source` and `(new_source, patch_text, not forwards) -> source`. | |
| - Before inserting, enforce the bound: if `current_count + 2 > maxsize`, evict `max(2, current_count // 4)` randomly chosen keys first. Use non-deterministic eviction so no particular key is guaranteed to survive. | |
| - `clear` empties the dictionary but does not alter `maxsize`. | |
| - Never return optional values; `retrieve` is a plain dict access. Callers must wrap it in `try/except KeyError`. | |
| - Check the cache before starting any subprocess or temporary-file work; a hit must do zero filesystem or subprocess activity. | |
| - Populate the cache only after a successful patch operation. A raised `ValueError` from the patch command must leave no new entries. | |
| - Key normalization is the caller's responsibility: the API dedents `patch_text` and source before cache lookup, so the cache itself should not re-dedent. | |
| - Keep the cache process-global and independent of function objects; it memoizes only source-string transformations. | |
| Example: | |
| ```python | |
| from patchy.cache import PatchingCache | |
| cache = PatchingCache(maxsize=4) | |
| src = "def f():\n return 1\n" | |
| new = "def f():\n return 2\n" | |
| patch_text = "@@ -1,2 +1,2 @@\n def f():\n- return 1\n+ return 2\n" | |
| cache.store(src, patch_text, True, new) | |
| assert cache.retrieve(src, patch_text, True) == new | |
| assert cache.retrieve(new, patch_text, False) == src | |
| cache.clear() | |
| ### Node: Additional components | |
| # Implementation constraints for patchy.api | |
| ## Functional requirements | |
| - Provide a real, importable module at `src/patchy/api.py` with runtime dotted path `patchy.api`. | |
| - Define `__all__ = ("patch", "mc_patchface", "unpatch", "replace", "temp_patch")` exactly, in that order. | |
| - Create the five public callables in this module. Their behavior is covered by the other capability docs; here only their residency matters. | |
| - Have `src/patchy/__init__.py` perform `from .api import *` so the top-level package re-exports the same objects governed by `__all__`. | |
| - At import time, create `_patching_cache = PatchingCache(maxsize=100)` (import `PatchingCache` from `patchy.cache`). | |
| - At import time, compute `FEATURE_MASK` by OR-ing `compiler_flag` for every name in `__future__.all_feature_names`. | |
| - At import time, create `_source_map = WeakKeyDictionary()` for storing modified sources by underlying function object. | |
| - Use `from __future__ import annotations` at the top so modern union syntax in annotations imports safely. | |
| - Ensure importing the module has no side effects beyond the listed internal setup; do not run `patch`, create tempdirs, or resolve dotted names at import time. | |
| - Keep `mc_patchface` as the same callable object as `patch` (`mc_patchface = patch`), assigned inside `api.py`. | |
| ## Minimal usage example | |
| ```python | |
| import patchy.api # must succeed with no external side effects | |
| print(patchy.api.__all__) # the five public names | |
| print(patchy.api.patch is patchy.api.mc_patchface) # True | |
| print(patchy.api._patching_cache.maxsize) # 100 | |
| from patchy import patch as top_level_patch | |
| assert top_level_patch is patchy.api.patch | |
| ``` | |
| ## Non-obvious notes | |
| - The weak-key `_source_map` must be a module singleton used by `patch`, `unpatch`, and `replace` (through `_get_source`/`_set_source`); the cache must be a module singleton used by `patch`, `unpatch`, and `temp_patch` (through `_apply_patch`), not `replace`. Do not allocate a new cache per call. | |
| - `PatchingCache(maxsize=100)` is the concrete instance behind all speed-up behavior; constructing it in the package `__init__` instead of `api.py` would still need to expose it to `api.py`, so keep construction in `api.py`. | |
| - The top-level package should not re-define or wrap the public functions; `from patchy import patch` and `import patchy.api; patchy.api.patch` must be the same object. | |