Download tasks/data/forward/aastopher__sutools.a1cb9bd/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 63.1 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/aastopher__sutools.a1cb9bd/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/aastopher__sutools.a1cb9bd/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/aastopher__sutools.a1cb9bd/instruction.md
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:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.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.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.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/repoat 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:
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:
{ [ -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 freshStorewhosefuncsdict is empty and whosecliandlogattributes areNone.benchy- a freshBenchywhosereportdict is empty.- the facade functions
register,cli,logger,log, which all close over the singlestoreobject (and, forbenchy, 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:
registerwrites intostore.funcs(viastore.add_func).clireadsstore.funcsandstore.log, then writes the resulting CLI back withstore.add_cli.loggerreadsstore.funcs(to derive default logger names) and forwards that derived list into theLoggerconstructor, then writes the resulting logger back withstore.add_log.logreadsstore.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, andstore.funcs[name]is a metadata dict with the keysfunc,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
@registertwice 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:
- If
store.logis truthy, constructCLI(desc, logs, store.log); otherwise constructCLI(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. 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.parse()- argument parsing happens immediately, insidecli(), before the store is updated. Code that readssys.argvruns here, so a test must patchsys.argvbefore callingsu.cli(), and any argparse error/exit (bad arguments,-h) surfaces from this call.- Within
parse(), a command present insys.argvis dispatched: the command is looked up in the snapshot dict, the registered function is called directly (asyncio.runfor coroutine functions), the return value is printed when it is truthy, and thensys.exit()is called. ThatSystemExitpropagates straight out ofparse(), sostore.add_cli(cli_obj)is never reached and the calling module never continues pastsu.cli(). store.add_cli(cli_obj)- reached only when no command was dispatched (an invocation whosesys.argvselects 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:
- Resolve the log path: without
filepath,os.path.join('logs', name, f'{filename}.log'); withfilepath,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. os.makedirsthe parent directory when it does not already exist (the'logs/<name>'tree is created even iffile=False).- Create
logging.FileHandler(filepath, 'w')when nofhandleris supplied - again regardless of thefileflag;'w'truncates an existing file with the same resolved path. - Choose the logger-name list. Only when the passed
loggersis falsy andstore.funcsis non-empty does the facade substitutelist(store.funcs.keys()); in every other case it forwardsloggersexactly as received - includingNone, which is that parameter's own default.Logger.__init__iterates the value it is given with no guard, so on a freshly imported package (emptyfuncs, no explicitloggers)su.logger(name='x')fails withTypeError: 'NoneType' object is not iterable. Because path resolution,os.makedirsandlogging.FileHandler(filepath, 'w')all run before theLoggeris constructed, that failure happens after thelogs/<name>directory already exists and the log file has already been created (or truncated), and it leavesstore.logunchanged -Noneon a fresh store, or the previous logger object. The empty-namespace situation (a logger whoseloggersnamespace carries no attributes) is reached only whenloggers=[]is passed explicitly; the default path can never produce it, because the forwardedNoneraises first. Tests against a store with emptyfuncsmust therefore either register a function beforehand or passloggers=[]explicitly. - Construct
Logger(...)with all thirteen values positionally, thenstore.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:
namedefaults toos.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.filenamedefaults todatetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')captured at import, so twologger()calls without an explicit filename reuse the same timestamp and therefore the same file.shandlerdefaults to a singlelogging.StreamHandler()instance andfilefmt/streamfmtdefault to singlelogging.Formatterinstances, 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
sutoolscreates no directories, files or log records; onlylogger()touches the disk. store,benchyand the four handler modules are the complete public surface required by the import contract; nothing is lazily loaded.benchyis an instance, used directly as a decorator (@su.benchy); it keeps areportdict mapping function name to a list of per-call records. It is process-global, so reports accumulate unless the test clearsreportor uses a freshBenchy.- Because
registerunwraps__wrapped__,@registerplaced 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 constructmeta_handler.Store()directly. logger()writes to the store only afterLogger(...)has been constructed, so a failure insideLogger- notably theloggers=NoneTypeError- leavesstore.loguntouched; it can still leave thelogs/<name>directory and a truncated.logfile behind, because those steps run first.cli()writesstore.clionly on a parse that returns without dispatching; a dispatched command prints its truthy result and raisesSystemExitbefore 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.inspectandsu.log_handler; tests rely on this to monkeypatchsu.os.makedirs/su.os.path.existsandsu.log_handler.atexit.register. A re-implementation that usesfrom os import ...or hides the handler modules would break those patches. logger()always opens a file handle (via the defaultlogging.FileHandler(filepath, 'w')) even whenfile=False, so patchingbuiltins.openis 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) toadd_funcs, so later mutations are visible throughcli_obj.func_dict, but the argparse subparsers were created from the snapshot taken duringadd_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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
- a set of stdlib
logging.Loggerobjects, one per requested logger name; - a throwaway container (
SimpleNamespace) that exposes those loggers by dot syntax so call sites read likesu.log().my_func.info("...")instead oflogging.getLogger("my_func"); - a configured output pipeline — at minimum a file handler (on by default), optionally a stream handler — plus optional retention policies that prune old
.logfiles.
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:
- 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 passname=explicitly whenever the name matters. - Resolve the file path. With no
filepath, the path becomeslogs/<name>/<filename>.log; with afilepath, 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). - Create parent directories.
os.makedirsruns on the resolved path's directory only when it does not already exist; no error handling wraps it, so an unwritable parent propagates out ofsu.logger(). - 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 aStringIO-backed handler or an in-memory fake). - Resolve the logger names. If
loggersis falsy and the store already contains registered functions, the store's function names are used; otherwise theloggersvalue is passed through unchanged. - Construct
Logger, which performs all namespace and handler wiring described below. - Store the
Loggerso thatsu.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 incomingloggersiterable, 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, androotloggerare stored on the instance; tests readlog_obj.nameandlog_obj.loggersdirectly.fhandler/shandlerkeep whatever was passed, includingNone. - Levels.
loglvlis 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; withloglvl=DEBUGall 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 viavars(ns). Wrapping the namespace conversion at exactly this point is observable: code that inspectslog_obj.loggerssees a namespace object, never a dict, and the handler-attachment loops iteratevars(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 getsloglvlandfilefmt; then, for every name in the namespace, the handler is added to that logger andlogger.propagateis set toFalse. 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 perLogger— 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, defaultFalse). Same shape:loglvlandstreamfmtare applied to the stream handler, then the handler is added to every logger andpropagateis disabled again. - Both enabled. Handlers are attached file-first, stream-second, so on a fresh process
logger.handlers[0]is the file handler andlogger.handlers[1]the stream handler. Several tests indexloggers.<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.registerstill fires once perLogger. - Neither enabled. No handlers are attached and
propagatestaysTrue; the loggers inherit whatever root configuration exists and keep theloglvlset on them. No teardown hook is registered. - Handler-level requirement. Each block calls a method on the corresponding handler unconditionally, so passing
file=Truewithfhandler=None(orstream=Truewithshandler=None) raisesAttributeError.su.logger()never hits this because it manufactures a default file handler; directLogger(...)construction in tests always pairsfile=Falsewithfhandler=None. - Shared default stream handler. The
shandlerdefault insu.logger()is a module-levelStreamHandler()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.
- 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.
- The file at
filepathis 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. - 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 defaultlogs/<name>/<timestamp>.loglayout 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=Nonedown toLogger, which iterates it — aTypeErroronNone. Register functions first, or passloggers=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=Truewith afilepathwhose parent chain is not creatable raises during directory creation, before any handler exists.- Duplicate names in
loggerscollapse into a single namespace key: the construction loop runs once per occurrence, but each occurrence stores the same cachedlogging.Loggerobject 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 iteratevars(self.loggers).keys()— the deduplicated namespace — so each enabled handler is attached exactly once to that logger, not twice. log_obj.nameis only the label; the stdlib logger names come fromloggers. Changingnameafter construction changes nothing about the loggers.cap()andtimeout()are public and callable on demand; calling either before a filepath exists (constructed withfilepath=None) fails onos.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 bothatexitteardown 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:
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
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-%Stimestamp;file=True,stream=False,loglvl=logging.INFO,filecap=None,filetimeout=None. - Path resolution: no
filepath→logs/<name>/<filename>.log; withfilepath→<filepath>/<name>/<filename>.log. Create the resolved directory withos.makedirsonly 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
fhandleris falsy. - Default logger names: when
loggersis falsy and the store holds registered functions, use the store's function names; otherwise passloggersthrough unchanged. Never substitute an empty list forNone. - Return the
Logger, then register it on the store sosu.log()can return its namespace. su.log()returns the store's logger namespace; before anysu.logger()call the namespace is absent (attribute error), and after a second call it reflects the newestLogger.- Re-configuration reuses the cached
logging.Loggerobjects: handlers accumulate on them (counts and indices shift, stale handlers bound to the previous path stay attached),propagate = Falseis re-applied, and each file-enabledLoggerregisters its ownatexitteardown 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
loglvlto 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 iteratevars(...).keys()(deduplicated, so duplicate input names attach each handler once). - File block (
filetruthy): set handler level tologlvl, set formatter tofilefmt, then for every logger add the handler and setpropagate = False; finally callatexit.register(self.out)exactly once for the object. - Stream block (
streamtruthy): set handler level tologlvl, set formatter tostreamfmt, then add the handler to every logger and setpropagate = False. No teardown registration here. - Attach file before stream so handler indices are stable on first configuration. Do not guard
setLevel/setFormattercalls againstNonehandlers:file=Truewithfhandler=Noneandstream=Truewithshandler=Nonemust raiseAttributeError. - Do not attach anything when both toggles are false; propagation stays enabled.
Retention
- Run cap before timeout, each gated on truthiness and type (
intfor cap,strfor timeout); wrong types are ignored without error, and0/""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 — twojoincalls plus onegetctimeper file.timeout()builds plain joined paths — onejoinper file, nogetctimewhile building the list — and callsos.path.getctimeper file later inside the comparison loop. - Cap: sort descending by creation time, keep the first
filecapentries, deletelogs[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; computenow - delta; delete files whosegetctimeis 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
KeyErroraround the timeout body and warn with aWarningnaming that character (case-sensitive). LetValueErrorfrom a missing amount propagate. cap()andtimeout()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.handlersduring 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
FileNotFoundErrorand 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-levelrmdir, not recursive. Each wrapped in its ownFileNotFoundErrorcatch 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
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")