Skip to content

fix: correct slice naming, argname star handling and frame errors; 6x speedup - #122

Merged
pwwang merged 2 commits into
masterfrom
audit-and-perf
Dec 1, 2026
Merged

pwwang merged 2 commits into
masterfrom
audit-and-perf

Conversation

@pwwang

@pwwang pwwang commented Dec 1, 2026

Copy link
Copy Markdown
Owner

Summary

Audit and performance pass over the library. Fixes ten failure cases across six defects that are proven broken on master, plus a 6x speedup on a representative workload. Every claim below was produced by running the code on both master and this branch.

Behaviour fixes

Each case fails on master and produces the correct result here.

Case master this branch
node_name() on a step-only slice c[::2] = f() named c[:]; c[1::2] named c[1:] step preserved
node_name() on nested subscripts c[[[1]]] and c[[1], [2]] raise TypeError named correctly
argname("*args", "multi") after a *args argument returns ('first','second','t','h','i','r','d') ('first','second','third')
frame index past the end of the stack AttributeError from executing VarnameRetrievingError
the same with raise_exc=False AttributeError None, as documented
negative frame index AttributeError VarnameRetrievingError
get_node_by_frame(None) AttributeError None
exec_code() with a bad ignore temp file left on disk cleaned up

Two hygiene fixes: make_readme.py leaked two codeblock_* temp files per run (now zero, measured at CLI level), and seven branches that could no longer be reached were removed (sys.version_info < (3, 8)/< (3, 9) shims and the PY311 guard around reconstruct_func_node), which pragma: no cover had been hiding from the coverage report.

The will() docstring named the wrong trigger for ImproperUseError. The Raises section said it fires when will() is not called inside a method or property of a class instance. That is false in both directions: it works in a plain free function, and it raises inside a method. The condition is whether the call site is followed by an attribute access. Reworded to say so.

Performance

A workload calling varname, nameof, argname and will 3000 times each, including a 16-frame stack and a decorator wrapper:

arm median min max
master 2.198s 2.008s 2.370s
this branch 0.359s 0.331s 0.390s

6.1x, over 11 interleaved rounds. The benchmark asserts both arms resolve to different implementations and print identical output, so a reading of 1.0x cannot come from two identical arms.

Four changes carry it, each measured alone before the next was stacked:

  • walk outer frames lazily over f_back instead of materialising a full inspect.getouterframes() list (with source lines) on every call
  • memoise path.realpath for frame filenames and for preset ignore paths
  • memoise inspect.signature for plain functions that have no __signature__
  • precompile the two argname regexes

One optimisation was measured and reverted: sharing the default IgnoreList elements bought 1.05x but changed IgnoreList.create().ignore_list == from False to True, so it is not in this branch.

fast-anything

fast-anything scan ranks varname.utils.get_node first at 61.9% cumtime, but port refuses it and every other hot function, because their arguments are frames and AST nodes rather than plain data:

recorded no usable calls to varname.utils.get_node out of 0.
Arguments and results must be plain data: numbers, strings, bytes, lists, tuples, dicts, sets

The ceiling was measured rather than assumed. A port replaces only a function's own time, so the best single candidate is worth 1.019x, and porting every candidate at 100% efficiency would remove 25.8% of the run. The 6x came from Python.

Testing

Gate Result
pytest on Python 3.9 / 3.10 / 3.11 / 3.12 / 3.13 / 3.14 91 passed on every leg
coverage 100%, 649 statements, 0 missed
flake8 varname clean
mypy -p varname no issues in 5 source files
make_readme.py README.raw.md vs README.md in sync
playground notebook 68 cells, no errors, runs from the repo root and from playground/
line endings LF only

New tests cover each fix above, which is why coverage stays at 100%.

Notes for the reviewer

  • The new out-of-range-frame tests document behaviour master did not have. They are here because the docstrings already promised VarnameRetrievingError, and raise_exc=False already promised None.
  • The notebook is re-executed in a second commit so the source change and the output churn are reviewable separately.
  • Nothing in this branch is a version bump or a release.

Several edge cases returned wrong results, or leaked an AttributeError out
of the `executing` dependency instead of raising the documented error:

- `node_name()` dropped the step of a step-only slice, so `c[::2] = f()`
  was named `c[:]`; nested subscripts (`c[[[1]]]`) raised TypeError
- `argname()` never cleared its `*` flag, so an argument that followed
  `*args` was expanded too: `argname("*args", "multi")` returned the
  characters of the value instead of its name
- a frame index past the end of the stack raised AttributeError rather
  than VarnameRetrievingError, and did not return None for
  `raise_exc=False`; a negative index did the same
- `get_node_by_frame(None)` raised AttributeError
- `exec_code()` left its temporary file on disk when the call failed
- `make_readme.py` leaked two `codeblock_*` files per run
- `will()`'s Raises section named the wrong trigger for ImproperUseError:
  the condition is whether the call site has an attribute, not whether the
  caller is a method of a class instance

Performance work in the same code paths. A workload that calls `varname`,
`nameof`, `argname` and `will` 3000 times each, including a 16-frame stack
and a decorator wrapper, went from 2.198s to 0.359s (6.0x, 11 interleaved
rounds, both arms asserted to print identical output):

- walk outer frames lazily over `f_back` instead of materialising a full
  `inspect.getouterframes()` list per call
- memoise `path.realpath` for frame filenames and preset ignore paths
- memoise `inspect.signature` for plain functions with no `__signature__`
- precompile the two `argname` regexes

The README documented `__setattr` where the attribute is `__setattr__`.
The notebook had not been executed since 2025-06-20, so its stored outputs
still pointed at `core.py:106` and `module_all_calls.py:6` while a later
`style:` commit had moved those lines to `:109` and `:7`.

- print the source of each `module_*.py` before the demo that ignores it,
  instead of importing a file the reader cannot see
- resolve the playground directory in the first cell, so the notebook runs
  from the repository root as well as from `playground/`
- replace the stale `# argname is superseded by argname` comment, a broken
  edit of "superseded by argname2" (`argname2` was removed in v0.12), with
  what `argname` actually takes
- re-execute and store the outputs: 68 cells, no errors
@pwwang
pwwang merged commit fc923dd into master Dec 1, 2026
10 checks passed
pwwang added a commit that referenced this pull request Dec 1, 2026
Behaviour changes from #122, plus one breaking change: a frame index past the
end of the call stack now raises VarnameRetrievingError instead of leaking an
AttributeError from `executing`, and returns None for `raise_exc=False`.

The version now lives only in `varname/__init__.py`. `pyproject.toml` declares
`dynamic = ["version"]` and `tool.hatch.version` points at that file, so a
release bumps one line instead of three files, and `uv.lock` no longer records
a version for the package at all.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant