freshcrate
Skin:/
Home > Uncategorized > pysource-minimize

pysource-minimize

minimize python source code to find bugs more easily

Why this rank:Strong adoptionHealthy release cadenceRelease freshness

Description

minimize python source code to find bugs more easily

README

pypi version Python Versions PyPI - Downloads GitHub Sponsors

pysource-minimize

If you build a linter, formatter or any other tool which has to analyse python source code you might end up searching bugs in pretty large input files.

pysource_minimize is able to remove everything from the python source which is not related to the problem.

CLI

You can use pysource-minimize from the command line like follow:

pysource-minimize --file bug.py --track "Assertion" -- python bug.py

This executes python bug.py and tries to find the string โ€œAssertionโ€ in the output. The ---file bug.py will be minimized as long as โ€œassertionโ€ is part of the output of the command. The --file option can be specified multiple times and there is also an --dir option which can be used to search directories recursively for Python files.

Warning

Be careful when you execute code which gets minimized. It might be that some combination of the code you minimize erases your hard drive or does other unintended things.

example

API

Example for single files:

>>> from pysource_minimize import minimize

>>> source = """
... def f():
...     print("bug"+"other string")
...     return 1+1
... f()
... """

>>> print(minimize(source, lambda new_source: "bug" in new_source))
"""bug"""

This example minimizes multiple files and searches for sets which have 2 common elements:

>>> from pathlib import Path
>>> from typing import Dict
>>> from pprint import pprint
>>> from pysource_minimize._minimize import minimize_all
>>> sources = {
...     Path("a.py"): """\
... l={1,81894,9874,89228,897985,897498,9879,9898}
...     """,
...     Path("b.py"): """\
... l={5,81894,9274,89218,897985,897298,9879,9898}
...     """,
...     Path("c.py"): """\
... l={0,81894,9874,89218,897985,897498,9879,9298}
...     """,
... }
>>> def check(sources: Dict[Path, str | None], current_filename: Path) -> bool:
...     # current_filename can be used for progress output
...     # print(f"working on {current_filename} ...")
...     sets = []
...     for source in sources.values():
...         if source is not None:
...             globals = {}
...             try:
...                 exec(source, globals)
...             except:
...                 return False
...             if "l" not in globals:
...                 return False
...             sets.append(globals["l"])
...     return (
...         len(sets) >= 2
...         and all(isinstance(s, set) for s in sets)
...         and len(set.intersection(*sets)) >= 2
...     )
...
>>> pprint(minimize_all(sources, checker=check))
{PosixPath('a.py'): None,
 PosixPath('b.py'): 'l = {81894, 0}',
 PosixPath('c.py'): 'l = {0, 81894}'}

You might think that there are no two zeros in the original sets. This problem can occur if your check function is not specific enough. pysource-minimize tries to minimize numbers and strings, does so for one of the sets and finds that it satisfies your check. It generates new code during the minimization and can only use the check function to know if the solution is correct. This kind of problem can be solved by using a more precise check function or a --track argument when using the CLI. For example, you can add a check that all numbers in the set must be non-zero. However, this problem will not occur if you are looking for real minimal examples that throw certain exceptions. The worst that can happen here is that pysource-minimize finds another example that triggers the same problem.

fixed check function
>>> from pathlib import Path
>>> from typing import Dict
>>> from pprint import pprint
>>> from pysource_minimize._minimize import minimize_all
>>> sources = {
...     Path("a.py"): """\
... l={1,81894,9874,89228,897985,897498,9879,9898}
...     """,
...     Path("b.py"): """\
... l={5,81894,9274,89218,897985,897298,9879,9898}
...     """,
...     Path("c.py"): """\
... l={0,81894,9874,89218,897985,897498,9879,9298}
...     """,
... }
>>> def check(sources: Dict[Path, str | None], current_filename: Path) -> bool:
...     # current_filename can be used for progress output
...     # print(f"working on {current_filename} ...")
...     sets = []
...     for source in sources.values():
...         if source is not None:
...             globals = {}
...             try:
...                 exec(source, globals)
...             except:
...                 return False
...             if "l" not in globals:
...                 return False
...             sets.append(globals["l"])
...     return (
...         len(sets) >= 2
...         and all(isinstance(s, set) for s in sets)
...         and len(result := set.intersection(*sets)) >= 2
...         and 0 not in result
...     )
...
>>> pprint(minimize_all(sources, checker=check))
{PosixPath('a.py'): None,
 PosixPath('b.py'): 'l = {81894, 89218}',
 PosixPath('c.py'): 'l = {81894, 89218}'}

Sponsors

I would like to thank my sponsors. Without them, I would not be able to invest so much time in my projects.

Silver sponsor ๐Ÿฅˆ

logfire

Similar projects

  • shrinkray which can not only minimize python code but C, C++, JSON and Dimacs too.

Release History

VersionChangesUrgencyDate
v0.10.1### Fix - set Interpolation.str to the unparsed valueLow8/30/2025
v0.10.0### Feat - **3.14**: added support for template-strings ### Fix - try to minimize Subscript to Name in Store contextLow8/29/2025
v0.9.0### Feat - implemented minimize_all() - better minimization for ast.AnnAssign - better minimization for ast.AugAssign - try to replace every ast.expr with ast.Constant(0) - replace names with unique_name_N if possible to show where a common name matters ### Refactor - fixed typosLow7/5/2025
v0.8.0## v0.8.0 (2025-04-16) ### Feat - new cli with visual feedback https://github.com/user-attachments/assets/cfcd9a68-7e8c-4aae-ade2-c7325106916a ### Fix - minimize MatchValue.value - minimize Raise.exc - minimize Call.func - also minimize left side of an assertion - improved comprehesion minimization - NamedConstant has been removed in 3.14 ### Refactor - improved pattern minimization **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.7.0Low4/16/2025
v0.7.0## What's Changed * cpython 3.13 support by @15r10nk in https://github.com/15r10nk/pysource-minimize/pull/19 * fix: add missing license file by @15r10nk in https://github.com/15r10nk/pysource-minimize/pull/20 **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.6.3...v0.7.0Low10/9/2024
v0.6.3## What's Changed - Improve error reporting when source cannot be minimized (#16) @AlexWaygood - Complete type hints for public API (#15) @AlexWaygood **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.6.2...v0.6.3Low4/23/2024
v0.6.2## What's Changed fixed some corner cases with yield, MatchClass, default args and slices **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.6.1...v0.6.2Low3/25/2024
v0.6.1## What's Changed * Some fixes by @15r10nk in https://github.com/15r10nk/pysource-minimize/pull/11 **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.6.0...v0.6.1Low11/29/2023
v0.6.0## What's Changed ### Feat - removed python 3.7 support - minimize strings, bytes, int, float, boolean values - minimize nonlocal and global names - minimize type comments ### Fix - fix crash when minimizing raise statements - remove the upper dependency bounds in pyproject.toml - minimize kw_defaults correctly - minimize function defaults correctly - added py.typed **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.5.0...v0.6.0Low11/12/2023
v0.5.0## What's Changed * support for python 3.12 * some bug fixes **Full Changelog**: https://github.com/15r10nk/pysource-minimize/compare/v0.4.0...v0.5.0Low10/20/2023

Dependencies & License Audit

Loading dependencies...

Similar Packages

ai-dataset-generator๐Ÿค– Generate tailored AI training datasets quickly and easily, transforming your domain knowledge into essential training data for model fine-tuning.main@2026-06-06
dopEffectCSharp๐Ÿš€ Maximize your C# productivity with advanced techniques in strings, LINQ, and clean code, inspired by the book "Produtivo com C#."master@2026-06-06
COREA thing that uses AI to write perfect applications. For those who want to know how: a governance runtime enforcing immutable constitutional rules on AI coding agents.v2.6.0
antonMost advanced AI coworkerv2.26.5.29.4
BESSERA Python-based low-modeling low-code open-source platform for smart and AI-enhanced softwarev7.8.1

More in Uncategorized

modal-clientSDK libraries for Modal
gh-aw-firewallGitHub Agentic Workflows Firewall
llama.cppLLM inference in C/C++