File size: 63,080 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 | # aastopher/sutools
## Project Overview
sutools (short for "Super User tools") is a lightweight Python utility package that supplies per-module conveniences for two chores that usually demand boilerplate: logging setup and module-level command line interfaces. It deliberately aims low, offering sensible defaults and a shallow learning curve rather than replacing argparse, logging, click, or similar full-featured libraries; projects needing deep configurability are pointed toward those tools instead.
The design centers on a single shared function registry. Applying the `@su.register` decorator to a function (sync or async, with optional type hints that are used to enforce and document CLI arguments) stores it in `meta_handler.Store`, a central object that every other utility reads from. From that store, `su.cli()` builds an argparse-based `CLI` in `cli_handler`, generating subcommands, help text, defaults, and variadic `*args`/`key=value` kwargs handling automatically. Likewise, `su.logger()` configures a `Logger` from `log_handler` with file and stream handlers, formatting, file retention caps, and timeouts, exposing named loggers through the `su.log()` helper so functions can log to a logger matching their own name or to custom names. A third component, `bench_handler.Benchy`, provides the `@su.benchy` decorator, which records per-call timing, arguments, kwargs, and results in a report dictionary.
The package is organized as these four handler modules plus a thin public facade in `sutools/__init__.py` that wires the global `store` and `benchy` instances together, with tests mirroring each handler.
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**: `sutools`
- **Package roots**: `.`
- **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 'setuptools>=42' wheel
(
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.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; };
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 --continue-on-collection-errors -o addopts= tests/test_bench_handler.py tests/test_cli_handler.py tests/test_log_handler.py tests/test_meta_handler.py tests/test_sutools.py)
if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_bench_handler.py tests/test_cli_handler.py tests/test_log_handler.py tests/test_meta_handler.py tests/test_sutools.py); fi
collect=(python3 -m pytest -q -o addopts= tests/test_bench_handler.py tests/test_cli_handler.py tests/test_log_handler.py tests/test_meta_handler.py tests/test_sutools.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 --continue-on-collection-errors -o addopts= tests/test_bench_handler.py tests/test_cli_handler.py tests/test_log_handler.py tests/test_meta_handler.py tests/test_sutools.py)
if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_bench_handler.py tests/test_cli_handler.py tests/test_log_handler.py tests/test_meta_handler.py tests/test_sutools.py); fi
collect=(python3 -m pytest -q -o addopts= tests/test_bench_handler.py tests/test_cli_handler.py tests/test_log_handler.py tests/test_meta_handler.py tests/test_sutools.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
```
.deepsource.toml
.github/workflows/publish.yml
.github/workflows/test.yml
.gitignore
LICENSE
README.md
codecov.yml
docs/Makefile
docs/make.bat
docs/requirements.txt
docs/source/conf.py
docs/source/helpers.rst
docs/source/index.rst
docs/source/sutools.rst
docs/source/usage.rst
pyproject.toml
readthedocs.yaml
requirements.txt
setup.py
sutools/__init__.py
sutools/bench_handler.py
sutools/cli_handler.py
sutools/log_handler.py
sutools/meta_handler.py
tox.ini
```
## 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: Package initialization and shared registry store
## Purpose
The package facade is the only place where the three stateful pieces of sutools are joined: the registry (`meta_handler.Store`), the benchmark recorder (`bench_handler.Benchy`) and the components that consume the registry's contents - `cli_handler.CLI`, which is handed `store.funcs` by the facade, and the facade functions themselves (`cli`, `logger`), which are the only code that reads `store.funcs`. `log_handler.Logger` is *not* a registry reader: it is constructed by the facade with a logger-name list that has already been resolved, and internally it only calls `logging.getLogger` once per name it is given. Keeping that direction of coupling straight matters, because a reimplementation that made `Logger` look up a store it is not given would break the single-store contract.
Importing the package must therefore be cheap, side-effect free with respect to the filesystem, and must produce three module-level singletons immediately:
- `store` - a fresh `Store` whose `funcs` dict is empty and whose `cli` and `log` attributes are `None`.
- `benchy` - a fresh `Benchy` whose `report` dict is empty.
- the facade functions `register`, `cli`, `logger`, `log`, which all close over the single `store` object (and, for `benchy`, expose the instance itself as the decorator).
The submodules `meta_handler`, `cli_handler`, `log_handler`, `bench_handler` must be importable both as `from sutools import meta_handler` and as attributes of the package, because the facade imports them with `from sutools import ...` (i.e. re-export through the package namespace) rather than through relative imports. This makes the import order inside the facade significant: the four handler modules are imported on the first line, before any singleton is constructed, so `Store()` and `Benchy()` are available for instantiation.
## Relationship between the components
The Store is the single source of truth and the only mutable global state:
1. `register` writes into `store.funcs` (via `store.add_func`).
2. `cli` reads `store.funcs` and `store.log`, then writes the resulting CLI back with `store.add_cli`.
3. `logger` reads `store.funcs` (to derive default logger names) and forwards that derived list into the `Logger` constructor, then writes the resulting logger back with `store.add_log`.
4. `log` reads `store.log.loggers` - it does not create anything.
`cli_handler.CLI` and the facade functions are the only registry readers. `Logger` never sees the store: it receives a plain list of names and nothing else, so the coupling between the registry and logging is one-way and resides entirely in the facade.
Because there is exactly one store per interpreter, every utility in the package is implicitly coupled to the same registry. Re-importing `sutools` (or importing it from another test module) does not create a second store: Python caches the module, so registrations and the active CLI/logger objects persist for the whole process. Tests that assert on counts of `store.funcs` or on `benchy.report` therefore observe accumulated state, and a re-registration of a function with an already-used name replaces the previous entry rather than adding one.
## Registration semantics
`register` is a pass-through decorator: it inspects `getattr(func, "__wrapped__", func)` (so decorating an already-wrapped function - for instance the wrapper produced by `@benchy` - registers the *original* function and its name), records that original in the store, and returns the object it was given unchanged. Consequences that matter to tests:
- The decorated name still refers to the same callable object; no wrapper, no signature change, no docstring loss.
- The registry key is `func.__name__` of the original function, and `store.funcs[name]` is a metadata dict with the keys `func`, `names`, `types`, `defaults`, `desc`, `variadic`.
- Registering the same name twice silently overwrites (dict `update`), which keeps the last registration's metadata.
- Because the returned object is not marked in any way, applying `@register` twice to the same function is idempotent in effect (same key, same metadata).
Metadata extraction is delegated to `Store.add_func` and is entirely signature driven: positional parameter names come from `inspect.getfullargspec(func).args`, defaults come from `inspect.signature` (only parameters whose default is not `inspect.Parameter.empty`), annotations become `types`, and the docstring, when present, becomes `desc` (otherwise `None`). Variadic handling is the subtle part: the code walks `inspect.signature(func).parameters` in order and, for each parameter whose kind is `VAR_POSITIONAL` (`*args`) or `VAR_KEYWORD` (`**kwargs`), appends `str(param)` - which renders with its star, e.g. `*args` - to `names` and blanks `types` to `{}`. The `variadic` flag is assigned on *every* loop iteration, so its final value reflects only the **last** parameter of the signature. A function ending in `**kwargs` or `*args` is reported as variadic; a function such as `f(a, *args, key=1)` ends with a keyword-only parameter and is reported as non-variadic even though `*args` was appended to `names`. Any test asserting on `variadic` must take the trailing parameter into account.
`add_func` calls `inspect.getfullargspec`, so callables without an introspectable Python signature (built-ins, some C functions, `functools.partial` objects) are not suitable for registration; ordinary functions, lambdas and coroutine functions are.
## CLI construction ordering
`cli(desc, logs)` is a one-shot builder with a strict internal order that must be preserved:
1. If `store.log` is truthy, construct `CLI(desc, logs, store.log)`; otherwise construct `CLI(desc, logs)` (two-argument form, leaving the log object at its own default). This means the logger must be created *before* the CLI if CLI-side logging is wanted.
2. `add_funcs(store.funcs)` - the CLI snapshots the registry that exists at call time, in the sense that the argparse subparsers are built from it; functions registered later are not visible as subcommands of that CLI object.
3. `parse()` - argument parsing happens immediately, inside `cli()`, before the store is updated. Code that reads `sys.argv` runs here, so a test must patch `sys.argv` *before* calling `su.cli()`, and any argparse error/exit (bad arguments, `-h`) surfaces from this call.
4. Within `parse()`, a command present in `sys.argv` is *dispatched*: the command is looked up in the snapshot dict, the registered function is called directly (`asyncio.run` for coroutine functions), the return value is printed when it is truthy, and then `sys.exit()` is called. That `SystemExit` propagates straight out of `parse()`, so `store.add_cli(cli_obj)` is never reached and the calling module never continues past `su.cli()`.
5. `store.add_cli(cli_obj)` - reached only when no command was dispatched (an invocation whose `sys.argv` selects no subcommand). Only on that path does the new CLI become the active one, and a repeated call replaces the previous object.
Because dispatch happens inside `parse()` and `parse()` precedes `add_cli`, a run that actually dispatches a command is precisely the case in which `store.cli` is *not* updated: it stays `None` on a fresh store, or keeps the previously stored object. `su.cli()` raising `SystemExit` is therefore the normal, successful outcome of a command invocation, and tests that exercise dispatched commands must catch or assert on it. Symmetrically, anything invoked during parsing sees the pre-existing `store.cli`, so do not rely on the store pointing at the new CLI from inside a dispatched function.
Handing the logger to the CLI also has a side effect on logging: when `logs` is falsy but a log object exists, the CLI raises the level of every logger in that namespace to `logging.CRITICAL + 1`, silencing them process-wide (they are shared `logging.getLogger` objects). Hence `su.cli(desc, logs=True)` must be used whenever CLI-triggered functions should emit records - as the integration test that registers a function calling `su.log().<name>.info(...)` demonstrates. Calling `cli()` with `logs=False` and then expecting those records is a silent no-op.
## Logger construction ordering
`logger(...)` is also a one-shot builder and mutates the filesystem:
1. Resolve the log path: without `filepath`, `os.path.join('logs', name, f'{filename}.log')`; with `filepath`, `os.path.join(filepath, name, f'{filename}.log')` - a supplied directory is always extended by the logger name and the filename, so the final file is always nested two levels below it.
2. `os.makedirs` the parent directory when it does not already exist (the `'logs/<name>'` tree is created even if `file=False`).
3. Create `logging.FileHandler(filepath, 'w')` when no `fhandler` is supplied - again regardless of the `file` flag; `'w'` truncates an existing file with the same resolved path.
4. Choose the logger-name list. Only when the passed `loggers` is falsy **and** `store.funcs` is non-empty does the facade substitute `list(store.funcs.keys())`; in every other case it forwards `loggers` exactly as received - *including `None`, which is that parameter's own default*. `Logger.__init__` iterates the value it is given with no guard, so on a freshly imported package (empty `funcs`, no explicit `loggers`) `su.logger(name='x')` fails with `TypeError: 'NoneType' object is not iterable`. Because path resolution, `os.makedirs` and `logging.FileHandler(filepath, 'w')` all run *before* the `Logger` is constructed, that failure happens after the `logs/<name>` directory already exists and the log file has already been created (or truncated), and it leaves `store.log` unchanged - `None` on a fresh store, or the previous logger object. The empty-namespace situation (a logger whose `loggers` namespace carries no attributes) is reached only when `loggers=[]` is passed explicitly; the default path can never produce it, because the forwarded `None` raises first. Tests against a store with empty `funcs` must therefore either register a function beforehand or pass `loggers=[]` explicitly.
5. Construct `Logger(...)` with all thirteen values positionally, then `store.add_log(log_obj)` and return it. Only one logger is active at a time; the newest wins and the previous object is dropped from the store (its handlers are not closed by the facade).
## Import-time default evaluation (important)
The default arguments of `logger` are evaluated once, when the package module is executed, not per call. Three of them are worth calling out:
- `name` defaults to `os.path.basename(inspect.stack()[-1].filename)[:-3]` - the bottom-most frame of the stack at import time (normally the entry-point script) with the last three characters (`.py`) stripped. This is a fixed string afterwards.
- `filename` defaults to `datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')` captured at import, so two `logger()` calls without an explicit filename reuse the same timestamp and therefore the same file.
- `shandler` defaults to a single `logging.StreamHandler()` instance and `filefmt`/`streamfmt` default to single `logging.Formatter` instances, all shared by every call that does not override them.
`log()` is a pure read of `store.log.loggers`; before any successful `logger()` call `store.log` is `None`, so `log()` raises `AttributeError`. It returns the active logger's namespace object itself - never a copy, never a missing value - whose attribute names are exactly the names the logger was built with. That can be an empty namespace only when `loggers=[]` was passed explicitly (or, equivalently, when names were derived from an empty registry, which the default path cannot reach because the forwarded `None` raises `TypeError` first).
## Non-obvious behaviours worth pinning in tests
- Importing `sutools` creates no directories, files or log records; only `logger()` touches the disk.
- `store`, `benchy` and the four handler modules are the complete public surface required by the import contract; nothing is lazily loaded.
- `benchy` is an instance, used directly as a decorator (`@su.benchy`); it keeps a `report` dict mapping function name to a list of per-call records. It is process-global, so reports accumulate unless the test clears `report` or uses a fresh `Benchy`.
- Because `register` unwraps `__wrapped__`, `@register` placed above `@benchy` (or vice versa) still registers under the plain function name; the store never sees the benchmark wrapper.
- State is never reset by the facade; a test needing a pristine registry must clear `store.funcs`, `store.cli`, `store.log`, or construct `meta_handler.Store()` directly.
- `logger()` writes to the store only after `Logger(...)` has been constructed, so a failure inside `Logger` - notably the `loggers=None` `TypeError` - leaves `store.log` untouched; it can still leave the `logs/<name>` directory and a truncated `.log` file behind, because those steps run first. `cli()` writes `store.cli` only on a parse that returns without dispatching; a dispatched command prints its truthy result and raises `SystemExit` *before* the store is touched, so the returned CLI object is never obtained on that path.
- Because the facade imports its dependencies as module objects, the package namespace exposes `su.os`, `su.logging`, `su.datetime`, `su.inspect` and `su.log_handler`; tests rely on this to monkeypatch `su.os.makedirs` / `su.os.path.exists` and `su.log_handler.atexit.register`. A re-implementation that uses `from os import ...` or hides the handler modules would break those patches.
- `logger()` always opens a file handle (via the default `logging.FileHandler(filepath, 'w')`) even when `file=False`, so patching `builtins.open` is required in tests that must not touch the disk.
- The store is shared with the CLI by value: the facade passes `store.funcs` (the live dict) to `add_funcs`, so later mutations are visible through `cli_obj.func_dict`, but the argparse subparsers were created from the snapshot taken during `add_funcs`.
#### Exact API Reference
#### `sutools.register`
- **Import Path**: `from sutools import register`
- **Required Test Import Paths**:
- sutools.register
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: function
- **Signature**:
```python
def register(func)
```
- **Behavior**: register a function to the store
#### `sutools.cli`
- **Import Path**: `from sutools import cli`
- **Required Test Import Paths**:
- sutools.cli
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: function
- **Signature**:
```python
def cli(desc=None, logs=False)
```
- **Behavior**: init cli and register to store
#### `sutools.logger`
- **Import Path**: `from sutools import logger`
- **Required Test Import Paths**:
- sutools.logger
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: function
- **Signature**:
```python
def logger(name=os.path.basename(inspect.stack()[-1].filename)[:-3], loggers=None, loglvl=logging.INFO, filename=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), filepath=None, filefmt=logging.Formatter('%(asctime)s, %(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S'), fhandler=None, filecap=None, filetimeout=None, file=True, streamfmt=logging.Formatter('%(asctime)s, %(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S'), shandler=logging.StreamHandler(), stream=False)
```
- **Behavior**: init logger object and register to store
#### `sutools.log`
- **Import Path**: `from sutools import log`
- **Required Test Import Paths**:
- sutools.log
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: function
- **Signature**:
```python
def log()
```
- **Behavior**: retrieve loggers namespace from store
#### `sutools.bench_handler.Benchy`
- **Import Path**: `from sutools.bench_handler import Benchy`
- **Required Test Import Paths**:
- sutools.bench_handler.Benchy
- **Exact Test Import Statements**:
- from sutools import bench_handler
- **Kind**: class
- **Signature**:
```python
class Benchy:
def __init__(self)
@staticmethod
def summarize(data)
def func_meta(self, data)
def __call__(self, func)
report: dict
```
- **Behavior**: decorator class for collecting benchmark reports
#### `sutools.cli_handler.CLI`
- **Import Path**: `from sutools.cli_handler import CLI`
- **Required Test Import Paths**:
- sutools.cli_handler.CLI
- **Exact Test Import Statements**:
- from sutools import cli_handler, log_handler, meta_handler
- from sutools import meta_handler, cli_handler, log_handler
- **Kind**: class
- **Signature**:
```python
class CLI:
def __init__(self, desc, logs, log_obj=None)
def add_funcs(self, func_dict)
def parse(self)
name: Any
parser: Any
subparsers: Any
func_dict: dict
log_obj: Any
input: Any
log: Any
```
- **Behavior**: object designed for swift module CLI configuration
#### `sutools.meta_handler.Store`
- **Import Path**: `from sutools.meta_handler import Store`
- **Required Test Import Paths**:
- sutools.meta_handler.Store
- **Exact Test Import Statements**:
- from sutools import cli_handler, log_handler, meta_handler
- from sutools import meta_handler, cli_handler, log_handler
- **Kind**: class
- **Signature**:
```python
class Store:
def __init__(self)
def add_func(self, func)
def add_cli(self, cli_obj)
def add_log(self, log_obj)
funcs: dict
cli: Any
log: Any
```
- **Behavior**: internal object for storing function dictionary
#### `sutools`
- **Import Path**: `sutools`
- **Required Test Import Paths**:
- sutools
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.
#### `sutools.bench_handler`
- **Import Path**: `from sutools import bench_handler`
- **Required Test Import Paths**:
- sutools.bench_handler
- **Exact Test Import Statements**:
- from sutools import bench_handler
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.
#### `sutools.benchy`
- **Import Path**: `from sutools import benchy`
- **Required Test Import Paths**:
- sutools.benchy
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: constant
- **Signature**:
```python
benchy: Any
```
- **Behavior**: Module-level value required by the test import contract.
#### `sutools.store`
- **Import Path**: `from sutools import store`
- **Required Test Import Paths**:
- sutools.store
- **Exact Test Import Statements**:
- import sutools as su
- **Kind**: constant
- **Signature**:
```python
store: Any
```
- **Behavior**: Module-level value required by the test import contract.
#### `sutools.cli_handler`
- **Import Path**: `from sutools import cli_handler`
- **Required Test Import Paths**:
- sutools.cli_handler
- **Exact Test Import Statements**:
- from sutools import cli_handler, log_handler, meta_handler
- from sutools import meta_handler, cli_handler, log_handler
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.
#### `sutools.log_handler`
- **Import Path**: `from sutools import log_handler`
- **Required Test Import Paths**:
- sutools.log_handler
- **Exact Test Import Statements**:
- from sutools import cli_handler, log_handler, meta_handler
- from sutools import log_handler
- from sutools import meta_handler, cli_handler, log_handler
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.
#### `sutools.meta_handler`
- **Import Path**: `from sutools import meta_handler`
- **Required Test Import Paths**:
- sutools.meta_handler
- **Exact Test Import Statements**:
- from sutools import cli_handler, log_handler, meta_handler
- from sutools import meta_handler, cli_handler, log_handler
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.
### Capability: Logger configuration and namespace creation
## Logger configuration and namespace creation
### Purpose and mental model
`su.logger()` is the single factory that builds a logging layer for a module and hands back a `log_handler.Logger` object. One call produces three things at once:
1. a set of stdlib `logging.Logger` objects, one per requested logger name;
2. a throwaway container (`SimpleNamespace`) that exposes those loggers by **dot syntax** so call sites read like `su.log().my_func.info("...")` instead of `logging.getLogger("my_func")`;
3. a configured output pipeline — at minimum a file handler (on by default), optionally a stream handler — plus optional retention policies that prune old `.log` files.
The default logger-name set is not a constant: it is derived from the shared registry. `su.logger()` with no `loggers=` argument asks the store for the names of every function registered so far, so the usual workflow is *register first, then configure logging*: `@su.register` a function per module, call `su.logger()` once, and every registered function automatically gets a logger whose name equals the function name. Because the name matches, `%(name)s` in the formatter prints the function name, and a function can fetch its own logger with `su.log().<func_name>` or, generically, with `logging.getLogger(__name__)`-style lookups against the same objects.
The store holds the resulting `Logger`; `su.log()` reads the store back and returns the namespace object. So the sequence *`su.logger()` → `su.log()`* is required: calling `su.log()` before any `su.logger()` call hits a `None` store slot and fails with `AttributeError`. Because the store only keeps one logging object, the namespace returned by `su.log()` is the one produced by the most recent `su.logger()` call; configuring logging twice replaces what `su.log()` yields (logger objects themselves survive, since `logging.getLogger` caches by name). That survival has consequences a re-implementation must reproduce: the second `Logger` attaches its file handler (and stream handler, if enabled) to the *same* cached `logging.Logger` objects, so each logger's `handlers` list **accumulates** — handler counts grow with every call and a later call's file handler is no longer at `handlers[0]`, while handlers bound to the previous path stay attached and keep receiving records. `propagate = False` is simply re-applied (idempotent), and `atexit.register(self.out)` fires once more for every file-enabled `Logger`, so several teardown callbacks queue up for the same process, each holding its own (older) file path.
### Order of operations inside the factory
A re-implementation must preserve this order, because later steps observe earlier ones:
1. **Choose the logger name.** Default is the stem (extension stripped) of the file name of the *outermost* stack frame (`inspect.stack()[-1]`), i.e. the entry-point script, not the immediate caller. Under a test runner or REPL this can be the runner's stem, so treat the default as "the program's file stem" and pass `name=` explicitly whenever the name matters.
2. **Resolve the file path.** With no `filepath`, the path becomes `logs/<name>/<filename>.log`; with a `filepath`, it becomes `<filepath>/<name>.log`. The logger name is always inserted as an intermediate directory, so each named logger family owns a folder. The default file name is a timestamp, so repeated runs do not clobber each other by name (though the file handler is opened in write mode and truncates whatever path it is given).
3. **Create parent directories.** `os.makedirs` runs on the resolved path's directory only when it does not already exist; no error handling wraps it, so an unwritable parent propagates out of `su.logger()`.
4. **Create the default file handler** if none was supplied, bound to the resolved path in write mode. Supplying `fhandler=` skips this and lets the caller point the pipeline elsewhere (for example at a `StringIO`-backed handler or an in-memory fake).
5. **Resolve the logger names.** If `loggers` is falsy *and* the store already contains registered functions, the store's function names are used; otherwise the `loggers` value is passed through unchanged.
6. **Construct `Logger`,** which performs all namespace and handler wiring described below.
7. **Store the `Logger`** so that `su.log()` can retrieve it.
Note the interaction between steps 4 and 5: the default `fhandler` is built from the *resolved* path, while the default name set is built from the *store*. A caller who overrides `filepath` but not `fhandler` still gets a file handler pointed at `<filepath>/<name>/<filename>.log`, and the directory is created before the handler opens the file.
### What the `Logger` constructor establishes
The constructor is a pure wiring routine: it mutates global logging state and returns `None`.
- **Logger records.** For each name, `logging.getLogger(name)` is called, `setLevel(loglvl)` is applied to it, the object is saved under that key, and the object is *also* added to the module-level root logger's handler list. That last step is deliberately odd: the named loggers are appended to the root logger as if they were handlers. The observable consequences are that the root logger's handler list grows with one entry per element of the incoming `loggers` iterable, and that a record logged directly to the root logger is routed into those named loggers before reaching any real handler. A faithful re-implementation must keep the call, because tests that inspect the root logger's handlers or that log at root level observe it.
- **Cached attributes.** `name`, `filename`, `filepath`, `loglvl`, `file`, `stream`, `filefmt`, `fhandler`, `streamfmt`, `shandler`, and `rootlogger` are stored on the instance; tests read `log_obj.name` and `log_obj.loggers` directly. `fhandler`/`shandler` keep whatever was passed, including `None`.
- **Levels.** `loglvl` is applied three times in total: to every named logger, to the root logger, and again to each enabled handler (file handler at construction of the file block, stream handler in the stream block). Level filtering therefore happens both at logger and handler granularity; with `loglvl=DEBUG` all five standard levels reach the handlers, which is what makes the "all levels appear in captured output" style assertions pass.
- **Namespace conversion.** The dict is replaced by `SimpleNamespace(**loggers)`. Dot access therefore works for keys that are valid Python identifiers; names containing dots, dashes, or starting with digits are retrievable only via `vars(ns)`. Wrapping the namespace conversion at exactly this point is observable: code that inspects `log_obj.loggers` sees a namespace object, never a dict, and the handler-attachment loops iterate `vars(self.loggers).keys()`.
### Handler attachment, both branches
The file and stream blocks are independent and each is entered only when its toggle is truthy.
- **File branch (`file=True`, the default).** The file handler gets `loglvl` and `filefmt`; then, for *every* name in the namespace, the handler is added to that logger and `logger.propagate` is set to `False`. Disabling propagation keeps records from travelling up to the root logger, which is why output is not duplicated even though the root logger was handed logger objects earlier. Finally, `atexit.register(self.out)` is called exactly once per `Logger` — not once per logger — so teardown is registered only in the file branch. A stream-only configuration therefore never cleans up log files at exit.
- **Stream branch (`stream=True`, default `False`).** Same shape: `loglvl` and `streamfmt` are applied to the stream handler, then the handler is added to every logger and `propagate` is disabled again.
- **Both enabled.** Handlers are attached file-first, stream-second, so on a fresh process `logger.handlers[0]` is the file handler and `logger.handlers[1]` the stream handler. Several tests index `loggers.<name>.handlers[0]` and read its `.stream`/formatter, so ordering is part of the contract — and it only holds for the first configuration of a given name, since repeat calls append behind existing entries. `atexit.register` still fires once per `Logger`.
- **Neither enabled.** No handlers are attached and `propagate` stays `True`; the loggers inherit whatever root configuration exists and keep the `loglvl` set on them. No teardown hook is registered.
- **Handler-level requirement.** Each block calls a method on the corresponding handler unconditionally, so passing `file=True` with `fhandler=None` (or `stream=True` with `shandler=None`) raises `AttributeError`. `su.logger()` never hits this because it manufactures a default file handler; direct `Logger(...)` construction in tests always pairs `file=False` with `fhandler=None`.
- **Shared default stream handler.** The `shandler` default in `su.logger()` is a module-level `StreamHandler()` instance created at import time and reused by every call that does not pass its own. Its stream is bound at construction (standard error by default) and the last call's level/formatter win for all loggers sharing it. Tests that assert on stream output always pass an explicit handler bound to a specific stream, which avoids both the shared instance and the import-time stream binding.
### Retention: cap and timeout
Both policies run after handler wiring, in the fixed order cap-then-timeout, and each is guarded by a truthiness *and* type check, so a non-integer `filecap` or a non-string `filetimeout` is silently ignored rather than rejected (`filecap=0` is also ignored because it is falsy).
**Cap.** The directory scanned is the *parent folder of `filepath`*, i.e. the per-name folder (`logs/<name>` or `<filepath>/<name>`) — never the drive root, and never a recursive walk. Every entry ending in `.log` is paired with `(joined path, creation time)`, the list is sorted by creation time descending, and if the count exceeds `filecap` the tail beyond index `filecap` is deleted, so the newest `filecap` files survive. Feedback goes to stdout: a single-line message when more than one file is removed, and a different single-line message when exactly one is. Tests count the `os.path.join` and `os.path.getctime` calls made while building the pairs (two joins and one `getctime` per file), so the pairing must be done in one comprehension per file rather than, say, joining inside `os.remove` only. Because the current log file is the newest, it is never among the victims; equal timestamps make the survivor set unspecified (the sort is descending but not stable in a defined way for ties).
**Timeout.** `filetimeout` is a compact `<amount><unit>` string such as `10d`. The final character selects the unit from a fixed map (`m` minutes, `h` hours, `d` days, `o` months, `y` years); months are computed as 30 days and years as 365 days; everything else falls through to `timedelta(**{unit: amount})`. The threshold is `now - delta` computed from the wall clock. The listing covers the same per-name folder with the same `.log` filter, but it is **paths-only**, not the cap's tuple scan: `timeout()` performs one `os.path.join` per `.log` entry and calls **no** `os.path.getctime` while building the list; the timestamp lookup happens later, per file, inside the comparison loop just before a possible `os.remove`. Reusing the cap-style tuple comprehension here would inflate the asserted `getctime` call count. A file is deleted when its creation time is **strictly less** than the threshold timestamp. Boundary cases matter: a file whose age equals the threshold exactly is kept, so with a fixed clock a `30m` timeout keeps a file created exactly 30 minutes ago, and a file created exactly 5 hours ago survives a `5h` timeout. Background logs older than the threshold go regardless of name. After deletion a single summary line is printed naming how many files were removed; if nothing was removed, nothing is printed.
The whole timeout body sits inside a `try/except KeyError` that issues a `Warning` naming the offending last character. Two consequences: an unknown unit (case-sensitive — `M`, `H`, etc. are invalid) is a warning, not an error, and any unrelated `KeyError` raised in the body is reported the same way. Malformed strings are not protected — an empty amount (`"d"`) makes the integer conversion fail with `ValueError`, which escapes.
### Teardown semantics of `out()`
`out()` is both a public method and the `atexit` callback, so its effect is observed after any program that used file logging finishes.
1. Every logger in the namespace is checked for handlers; if it has any, each handler is closed and the handler list is emptied. This detaches the file handler so the file can be removed on platforms that lock open files. Only the named loggers' *own* handler lists are touched: the logger objects that construction appended to the root logger's handler list are **left there**, and no other root logger state is reset, so after teardown the root logger still lists one (now handler-less) logger object per construction element. A re-implementation must not "clean this up"; assertions that inspect the root logger's handlers depend on it.
2. The file at `filepath` is stat'ed; if its size is zero it is deleted. A missing file is caught and reported as a printed "failed to remove file" line carrying the exception text — the method never raises for that case.
3. The per-name folder (`dirname(filepath)`) is removed if it is empty, then the folder above it is removed if *that* is empty. These two steps are what make the default `logs/<name>/<timestamp>.log` layout clean itself up when nothing was written. Missing folders are caught and reported with distinct "failed to remove module folder" / "failed to remove log folder" printed lines.
Both folder checks use the same try/except pattern and print rather than raise. Note that the empty-folder removal is unconditional with respect to the empty-file check: if a non-empty log file is kept, the folder is non-empty and survives.
### Practical workflow
A typical module-level setup registers its functions, configures logging once with a chosen level, formatter, and retention policy, then instruments handlers with `su.log().<name>`. Because `su.log()` returns a namespace, it can be called repeatedly at any time (it re-reads the store each call) but always reflects the last `su.logger()` invocation. To keep logs out of the default timestamped file, set `file=False` — but then no teardown is registered and, unless `stream=True`, nothing is attached at all. To send records only to a stream, pass `stream=True` with an explicit `shandler` bound to the desired stream. To keep a bounded history, set `filecap` to an integer and/or `filetimeout` to a duration string; both apply per logger-name folder at configuration time, meaning long-lived processes that rotate files themselves will not re-prune until the next `su.logger()` call.
### Edge cases worth encoding in tests
- Configuring logging before any function is registered passes `loggers=None` down to `Logger`, which iterates it — a `TypeError` on `None`. Register functions first, or pass `loggers=` explicitly.
- The generated default file name has second resolution, so two `su.logger()` calls in the same second resolve to the same path; the second file handler truncates it.
- `file=True` with a `filepath` whose parent chain is not creatable raises during directory creation, before any handler exists.
- Duplicate names in `loggers` collapse into a single namespace key: the construction loop runs once per occurrence, but each occurrence stores the same cached `logging.Logger` object under that key, so the last write simply overwrites with an identical object. The duplication is therefore observable *only* in the root logger's handler list, where that logger object appears once per occurrence. The file and stream blocks iterate `vars(self.loggers).keys()` — the deduplicated namespace — so each enabled handler is attached exactly **once** to that logger, not twice.
- `log_obj.name` is only the label; the stdlib logger names come from `loggers`. Changing `name` after construction changes nothing about the loggers.
- `cap()` and `timeout()` are public and callable on demand; calling either before a filepath exists (constructed with `filepath=None`) fails on `os.path.dirname(None)`.
- A second `su.logger()` for the same names does not start from a clean logger: handler entries accumulate on the cached loggers, the new file handler sits after the old one, and both `atexit` teardown hooks are registered.
#### Exact API Reference
#### `sutools.log_handler.Logger`
- **Import Path**: `from sutools.log_handler import Logger`
- **Required Test Import Paths**:
- sutools.log_handler.Logger
- **Exact Test Import Statements**:
- from sutools import cli_handler, log_handler, meta_handler
- from sutools import log_handler
- from sutools import meta_handler, cli_handler, log_handler
- **Kind**: class
- **Signature**:
```python
class Logger:
def __init__(self, name, loggers, loglvl, filename, filepath, filefmt, fhandler, filecap, filetimeout, file, streamfmt, shandler, stream)
def cap(self, filecap)
def timeout(self, filetimeout)
def out(self)
name: Any
loggers: dict
filename: Any
filepath: Any
loglvl: Any
file: Any
stream: Any
rootlogger: Any
filefmt: Any
fhandler: Any
streamfmt: Any
shandler: Any
```
- **Behavior**: object designed for swift granular logging configuration
## Detailed Implementation Nodes
### Node: Package initialization and shared registry store
## Functional constraints
**Module initialisation.** The facade module must, in this order: import the four handler modules through the package namespace; import `inspect`, `os`, `logging`, `datetime`; bind `store` to a new `meta_handler.Store()`; bind `benchy` to a new `bench_handler.Benchy()`. Import must not create directories, files, log records or argparse parsers.
**Store contract.** `Store.__init__` sets `funcs = {}`, `cli = None`, `log = None`. `add_func(func)` computes `names = inspect.getfullargspec(func).args`, `types = getfullargspec(func).annotations`, `defaults = {p.name: p.default for p in signature.parameters if default is not empty}`, `desc = func.__doc__` (else `None`), then walks `inspect.signature(func).parameters`; for every `VAR_POSITIONAL`/`VAR_KEYWORD` parameter append `str(param)` to `names` and set `types = {}`, and assign `variadic` on each iteration (final value = kind of the last parameter). Store `{'func','names','types','defaults','desc','variadic'}` under `func.__name__` via `dict.update` (same name overwrites). `add_cli`/`add_log` simply replace `cli`/`log`.
**register(func).** Register `getattr(func, '__wrapped__', func)` and return the argument unchanged. Never wrap, never re-key.
**cli(desc, logs).** Pass `store.log` as the third constructor argument when it is truthy, else use the two-argument constructor; then `add_funcs(store.funcs)`, then `parse()`, then `store.add_cli(cli_obj)`, then return the object. The function snapshot is taken at call time. `parse()` also dispatches: when `sys.argv` names a command it calls the registered function (via `asyncio.run` for coroutine functions), prints a truthy return value and raises `SystemExit`, which escapes before `store.add_cli` runs - so the store assignment happens only on a parse with no dispatched command, and `store.cli` keeps its previous value (often `None`) on command runs. A falsy `logs` together with a live log object must demote every logger in that namespace to `logging.CRITICAL + 1`.
**logger(...).** Resolve the path as `join(filepath or 'logs', name, f'{filename}.log')`; `os.makedirs` the parent when absent; default `fhandler = logging.FileHandler(filepath, 'w')`; choose `loggers = list(store.funcs.keys())` only when the passed `loggers` is falsy **and** `store.funcs` is non-empty, otherwise forward `loggers` verbatim (so a fresh store forwards `None`); construct `Logger` with the thirteen values positionally; `store.add_log`, return it. Directory creation and file-handler creation happen even when `file=False`, and they happen before `Logger` is constructed, so a `TypeError` from iterating `None` surfaces after the directory and file exist, with `store.log` left unchanged; only an explicit `loggers=[]` yields a namespaceless logger.
**log().** Return `store.log.loggers`, a `SimpleNamespace` whose attributes are the resolved logger names; propagate `AttributeError` when no logger exists. Not a copy.
**Defaults.** `name` and `filename` defaults are evaluated once at package import (`inspect.stack()[-1].filename` basename minus the trailing `.py`; `now()` formatted `%Y-%m-%d_%H-%M-%S`), as are the shared `Formatter` and `StreamHandler` instances; repeated calls reuse them.
**Isolation.** No reset logic exists; tests must clear `store.funcs`/`cli`/`log` and `benchy.report` themselves, or instantiate fresh `Store`/`Benchy` objects. The facade must keep `os`, `logging`, `datetime`, `inspect` and the handler modules reachable as package attributes so `monkeypatch.setattr(su.os, ...)` and `su.log_handler.atexit.register` patches take effect, and `logger()` must go through `os.path.join`/`os.makedirs`/`os.path.exists` plus `logging.FileHandler(filepath, 'w')` even with `file=False`. `Logger` must stay store-agnostic: it consumes the name list it is handed and never reaches back into `store.funcs`.
## Usage example
```python
import sutools as su
@su.register
def add(a: int, b: int = 2, *rest):
'''add numbers'''
return a + b + sum(rest)
assert su.store.funcs['add']['defaults'] == {'b': 2}
assert su.store.funcs['add']['desc'] == 'add numbers'
log = su.logger(name='demo', filepath='tmp_logs', filename='run') # tmp_logs/demo/run.log
assert su.store.log is log and 'add' in vars(su.log())
# with sys.argv selecting no subcommand: parse() returns and the store is updated
cli_obj = su.cli('demo cli', logs=True)
assert su.store.cli is cli_obj
```
If `sys.argv` names a registered command instead, `su.cli()` dispatches that function, prints a truthy result and raises `SystemExit`, so `store.cli` is never set on that path and the assertions above would not run. If the registration above were removed, `su.logger(name='demo')` would raise `TypeError` (forwarded `loggers=None`) after creating the directory and file; passing `loggers=[]` explicitly is the way to build a deliberately nameless logger.
### Node: Logger configuration and namespace creation
## Implementation constraints
**Factory (`su.logger`)**
- Signature defaults must remain lazy where required: name default derives from the outermost stack frame's file stem; file-name default is a `%Y-%m-%d_%H-%M-%S` timestamp; `file=True`, `stream=False`, `loglvl=logging.INFO`, `filecap=None`, `filetimeout=None`.
- Path resolution: no `filepath` → `logs/<name>/<filename>.log`; with `filepath` → `<filepath>/<name>/<filename>.log`. Create the resolved directory with `os.makedirs` only when absent. Resolve the path *before* building the default handler and *after* resolving the logger name.
- Default file handler: opened on the resolved path in write mode, created only when `fhandler` is falsy.
- Default logger names: when `loggers` is falsy and the store holds registered functions, use the store's function names; otherwise pass `loggers` through unchanged. Never substitute an empty list for `None`.
- Return the `Logger`, then register it on the store so `su.log()` can return its namespace.
- `su.log()` returns the store's logger namespace; before any `su.logger()` call the namespace is absent (attribute error), and after a second call it reflects the newest `Logger`.
- Re-configuration reuses the cached `logging.Logger` objects: handlers accumulate on them (counts and indices shift, stale handlers bound to the previous path stay attached), `propagate = False` is re-applied, and each file-enabled `Logger` registers its own `atexit` teardown hook.
**Constructor wiring order**
- Assign the exposed attributes (`name`, `filename`, `filepath`, `loglvl`, `file`, `stream`, `filefmt`, `fhandler`, `streamfmt`, `shandler`, `rootlogger`, `loggers`) before any loop, so partial failures leave the same observable attributes as a completed construction.
- Per name: `logging.getLogger(name)`, `setLevel(loglvl)`, store in the dict, and append the *logger object* to the root logger's handlers. Keep this append; it is externally visible, and it runs once per element of the incoming iterable even when names repeat.
- Apply `loglvl` to the root logger once, after populating the dict.
- Convert the dict to `SimpleNamespace(**dict)` — the attribute name is a namespace for the rest of the object's life, and later loops iterate `vars(...).keys()` (deduplicated, so duplicate input names attach each handler once).
- File block (`file` truthy): set handler level to `loglvl`, set formatter to `filefmt`, then for every logger add the handler and set `propagate = False`; finally call `atexit.register(self.out)` exactly once for the object.
- Stream block (`stream` truthy): set handler level to `loglvl`, set formatter to `streamfmt`, then add the handler to every logger and set `propagate = False`. No teardown registration here.
- Attach file before stream so handler indices are stable on first configuration. Do not guard `setLevel`/`setFormatter` calls against `None` handlers: `file=True` with `fhandler=None` and `stream=True` with `shandler=None` must raise `AttributeError`.
- Do not attach anything when both toggles are false; propagation stays enabled.
**Retention**
- Run cap before timeout, each gated on truthiness and type (`int` for cap, `str` for timeout); wrong types are ignored without error, and `0`/`""` are ignored because falsy.
- Both scan `os.path.dirname(self.filepath)` (the per-name folder) with a non-recursive listing filtered to names ending in `.log`, but they build their lists differently and the call counts are asserted. `cap()` builds `(os.path.join(folder, f), os.path.getctime(os.path.join(folder, f)))` tuples — two `join` calls plus one `getctime` per file. `timeout()` builds plain joined paths — one `join` per file, **no** `getctime` while building the list — and calls `os.path.getctime` per file later inside the comparison loop.
- Cap: sort descending by creation time, keep the first `filecap` entries, delete `logs[filecap:]`. Print one line reporting the number removed when several were removed and a different single line when exactly one was.
- Timeout: parse trailing unit `m|h|d|o|y` (minutes, hours, days, months = 30 days, years = 365 days) and leading integer amount; compute `now - delta`; delete files whose `getctime` is strictly less than the threshold timestamp (equal-to-threshold files survive). Print a count line only when at least one file was removed.
- Invalid unit character: catch `KeyError` around the timeout body and warn with a `Warning` naming that character (case-sensitive). Let `ValueError` from a missing amount propagate.
- `cap()` and `timeout()` stay public and callable at will.
**Teardown (`out`)**
- For each logger in the namespace: if it has handlers, close each one and reset its handler list to empty.
- Do not touch the root logger: the logger objects appended to `rootlogger.handlers` during construction stay there after teardown (only the named loggers' own lists are cleared), and no other root state is reset.
- Stat the resolved file path; delete it when its size is zero. Catch `FileNotFoundError` and print the failure message with the exception text instead of raising.
- Then try to remove the parent folder (`dirname(filepath)`) if empty, then its parent if empty; single-level `rmdir`, not recursive. Each wrapped in its own `FileNotFoundError` catch printing a distinct folder-specific message.
- Never let teardown abort the remaining steps: a failure in the file removal must still allow both folder checks to run.
**Usage example**
```python
import sutools as su, logging
@su.register
def worker(msg):
su.log().worker.info(f"got {msg}") # logger name == function name
su.logger(loglvl=logging.DEBUG, filecap=5, filetimeout="10d")
su.log().worker.warning("wired to file + namespace")
```
|