Write reference documentation from source code.
Done by an agent. Checked twice.
A reference page covering every public function and argument, checked against the code, including where the code and its comments disagree.
Real files in
- LICENCE.txt
The library's MIT license text with its copyright line, unchanged. 20 lines, 1 KB. - number.py.txt
One whole source file, src/humanize/number.py from version 4.11.0 of the open source humanize library for Python, unchanged. 573 lines: eight public functions that turn numbers into readable text, plus one private helper. Trimmed to this one file out of the library.. 573 lines, 16 KB.
Real public documents. Links below.
Three steps
- 1.Read the code, not just its comments
- 2.Document every function and every argument
- 3.Write the reference
Claude Sonnet 5.5, 1 min 41 s. No web. It never saw the check.
Checked twice
- Passed: 8 of 8 public functions in the code have their own section in reference.md and 0 sections describe anything else
- Passed: 19 of 19 arguments in the code are listed in arguments.csv and 0 listed arguments are not in the code
- Passed: 19 of 19 arguments carry the type hint, the required flag and the default written in the code
- Passed: 19 of 19 arguments are described inside the section of their own function
- Passed: 55 of 55 example lines are copied from the code with the result the code shows and 8 of 8 functions have an example
- Passed: 1 of 1 errors raised in the code are named in the section of the function that raises them
- Passed: 19 of 19 arguments appear in the signature of their section with the type hint and default of the code and 8 of 8 return types match
- Passed: 1 of 1 copyright lines from the license file are repeated word for word in reference.md
Second review by Claude Opus 5.5: pass.
Then we broke a copy of the output 6 ways on purpose. The check caught 5.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `float` | yes | | Number to format. `None` is allowed by the code even though the hint says `float`. |
| format | `str` | no | `"{:}"` | A format string, used as `format.format(value)`, or a callable that takes the (possibly clamped) value and returns a string. The type hint says `str` only, but the code also accepts a callable. |
| floor | `float \| None` | no | `None` | Smallest value before clamping. `None` means no lower bound. |
| ceil | `float \| None` | no | `None` | Largest value before clamping. `None` means no upper bound. |
| floor_token | `str` | no | `"<"` | Text put in front when the value is below `floor`. |
| ceil_token | `str` | no | `">"` | Text put in front when the value is above `ceil`. |
Returns: the token plus the formatted value, as `str`. Cases where the result differs from the `str` hint:
- If `value` is `None`, it returns `None`, not a string.
- If `value` is NaN or infinite, it returns `"NaN"`, `"-Inf"` or `"+Inf"` before any clamping, so infinite values are not clamped to `floor` or `ceil`.How this was run
An AI agent on Claude Sonnet 5.5 was given a folder with the files below and a three-step flow, and nothing else. It had no web access and never saw the check. The check was written before the run and made stricter after it. It works the answer out again from the input files. Then Claude Opus 5.5 reviewed the result against the inputs. The input files are real public documents.
Run 1 of 1 on 1 December 2026. The agent took 1 min 41 s.
What the second review verified
- All 8 public functions (ordinal, intcomma, intword, apnumber, fractional, scientific, clamp, metric) have one `## ` section each, in code order. The private `_format_not_finite` has no section, and no other `## ` headings are used.
- arguments.csv has 19 rows, which matches 2+2+2+1+1+2+6+3 arguments in the code. Types and defaults match the signatures exactly, for example `ndigits` is `int | None` with default None, and `format` is `"{:}"` for clamp and `"%.1f"` for intword.
- All 55 `>>>` example lines match the docstrings word for word, including `metric(1e40)` → '1.00 x 10⁴⁰', which sits outside the Examples block. clamp's `raise ValueError(msg)` message is quoted exactly. The license line 'Copyright (c) 2010-2020 Jason Moiron and Contributors' is present.
- I re-ran the behaviour claims that go beyond the docstrings. `fractional(-1.5)` gives '-1 -1/2' because Fraction(-0.5) is -1/2. Precision -1 raises ValueError('Format specifier missing precision'). `float(10**400)` raises OverflowError. `clamp(None)` returns None, which contradicts the `str` hint. intword uses decillion up to 10^100 and returns plain digits at 10^100 or more.
What this run does not show
- The plain descriptions of what each function does are read only by the second review, so a wrong number in that text would pass the check.
- Nobody ran the module, so the check confirms the examples were copied from the code's own comments and not that they are true.
- This covers one file with 8 functions, so a larger module with classes was not tried.
Would the check catch a wrong answer?
A check that cannot fail proves nothing. After the run we took a copy of the output, broke it one small way at a time and ran the check again. It caught 5 of 6. The check was made stricter after the first try at this, and the same untouched output was graded again. It let these through, so on this job they rest on the second review alone:
- Changed the number 3,000 to 3,002 in reference.md
Open every file
flow.md · the three steps the agent followed
# Write reference documentation from source code function: product for: the engineer or technical writer who owns the developer documentation goal: A developer can use every public function of the module from the reference alone and nothing in it contradicts the code. ## 1. Read the code, not just its comments Read the code file in input/ (a Python module saved as text) and the license file beside it. List every function defined at the top level. A function whose name starts with an underscore is private: it gets no section of its own. For each public function read the signature, the docstring and the body. Where the docstring and the code disagree or the docstring leaves something out, the code wins. ## 2. Document every function and every argument For each public function record: - every argument in signature order, with its type hint copied exactly from the signature, whether it is required and its default copied exactly from the signature. - what the function returns, including any case where the body returns something the type hint does not say. - every error the body can raise and when. - at least one example. Copy examples only from the function's own docstring, each `>>>` line with the result line that follows it. Do not write examples of your own: you cannot run this code. Describe behaviour only from what the code does. If something cannot be told from the file, say so. ## 3. Write the reference Write output/reference.md. Start with a `# ` title, one short paragraph on what the module is for and the license and copyright line from the license file. Then one section per public function, in the order of the code. The heading is `## ` followed by the function name alone. Use `## ` headings for nothing else. Each section has the signature, a plain description, an arguments table, the return value, the errors and the examples in a code block. Write output/arguments.csv with columns function,argument,type,required,default. One row per argument of every public function. required is `yes` or `no`. default is empty for a required argument. ## Done looks like - Every public function has one section and every argument has one row. - Every type, default and example in the reference can be found in the code file. - No private function is presented as part of the public interface.
input/LICENCE.txt · 20 lines, 1 KB
Copyright (c) 2010-2020 Jason Moiron and Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
input/number.py.txt · 573 lines, 16 KB
"""Humanizing functions for numbers."""
from __future__ import annotations
import math
import re
import sys
from typing import TYPE_CHECKING
from .i18n import _gettext as _
from .i18n import _ngettext, decimal_separator, thousands_separator
from .i18n import _ngettext_noop as NS_
from .i18n import _pgettext as P_
if TYPE_CHECKING:
if sys.version_info >= (3, 10):
from typing import TypeAlias
else:
from typing_extensions import TypeAlias
# This type can be better defined by typing.SupportsInt, typing.SupportsFloat
# but that's a Python 3.8 only typing option.
NumberOrString: TypeAlias = "float | str"
def _format_not_finite(value: float) -> str:
"""Utility function to handle infinite and nan cases."""
if math.isnan(value):
return "NaN"
if math.isinf(value) and value < 0:
return "-Inf"
if math.isinf(value) and value > 0:
return "+Inf"
return ""
def ordinal(value: NumberOrString, gender: str = "male") -> str:
"""Converts an integer to its ordinal as a string.
For example, 1 is "1st", 2 is "2nd", 3 is "3rd", etc. Works for any integer or
anything `int()` will turn into an integer. Anything else will return the output
of str(value).
Examples:
```pycon
>>> ordinal(1)
'1st'
>>> ordinal(1002)
'1002nd'
>>> ordinal(103)
'103rd'
>>> ordinal(4)
'4th'
>>> ordinal(12)
'12th'
>>> ordinal(101)
'101st'
>>> ordinal(111)
'111th'
>>> ordinal("something else")
'something else'
>>> ordinal([1, 2, 3]) == "[1, 2, 3]"
True
```
Args:
value (int, str, float): Integer to convert.
gender (str): Gender for translations. Accepts either "male" or "female".
Returns:
str: Ordinal string.
"""
try:
if not math.isfinite(float(value)):
return _format_not_finite(float(value))
value = int(value)
except (TypeError, ValueError):
return str(value)
if gender == "male":
t = (
P_("0 (male)", "th"),
P_("1 (male)", "st"),
P_("2 (male)", "nd"),
P_("3 (male)", "rd"),
P_("4 (male)", "th"),
P_("5 (male)", "th"),
P_("6 (male)", "th"),
P_("7 (male)", "th"),
P_("8 (male)", "th"),
P_("9 (male)", "th"),
)
else:
t = (
P_("0 (female)", "th"),
P_("1 (female)", "st"),
P_("2 (female)", "nd"),
P_("3 (female)", "rd"),
P_("4 (female)", "th"),
P_("5 (female)", "th"),
P_("6 (female)", "th"),
P_("7 (female)", "th"),
P_("8 (female)", "th"),
P_("9 (female)", "th"),
)
if value % 100 in (11, 12, 13): # special case
return f"{value}{t[0]}"
return f"{value}{t[value % 10]}"
def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
"""Converts an integer to a string containing commas every three digits.
For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some
compatibility with Django's `intcomma`, this function also accepts floats.
Examples:
```pycon
>>> intcomma(100)
'100'
>>> intcomma("1000")
'1,000'
>>> intcomma(1_000_000)
'1,000,000'
>>> intcomma(1_234_567.25)
'1,234,567.25'
>>> intcomma(1234.5454545, 2)
'1,234.55'
>>> intcomma(14308.40, 1)
'14,308.4'
>>> intcomma("14308.40", 1)
'14,308.4'
>>> intcomma(None)
'None'
```
Args:
value (int, float, str): Integer or float to convert.
ndigits (int, None): Digits of precision for rounding after the decimal point.
Returns:
str: String containing commas every three digits.
"""
thousands_sep = thousands_separator()
decimal_sep = decimal_separator()
try:
if isinstance(value, str):
value = value.replace(thousands_sep, "").replace(decimal_sep, ".")
if not math.isfinite(float(value)):
return _format_not_finite(float(value))
if "." in value:
value = float(value)
else:
value = int(value)
else:
if not math.isfinite(float(value)):
return _format_not_finite(float(value))
float(value)
except (TypeError, ValueError):
return str(value)
if ndigits is not None:
orig = "{0:.{1}f}".format(value, ndigits)
else:
orig = str(value)
orig = orig.replace(".", decimal_sep)
while True:
new = re.sub(r"^(-?\d+)(\d{3})", rf"\g<1>{thousands_sep}\g<2>", orig)
if orig == new:
return new
orig = new
powers = [10**x for x in (3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 100)]
human_powers = (
NS_("thousand", "thousand"),
NS_("million", "million"),
NS_("billion", "billion"),
NS_("trillion", "trillion"),
NS_("quadrillion", "quadrillion"),
NS_("quintillion", "quintillion"),
NS_("sextillion", "sextillion"),
NS_("septillion", "septillion"),
NS_("octillion", "octillion"),
NS_("nonillion", "nonillion"),
NS_("decillion", "decillion"),
NS_("googol", "googol"),
)
def intword(value: NumberOrString, format: str = "%.1f") -> str:
"""Converts a large integer to a friendly text representation.
Works best for numbers over 1 million. For example, 1_000_000 becomes "1.0 million",
1200000 becomes "1.2 million" and "1_200_000_000" becomes "1.2 billion". Supports up
to decillion (33 digits) and googol (100 digits).
Examples:
```pycon
>>> intword("100")
'100'
>>> intword("12400")
'12.4 thousand'
>>> intword("1000000")
'1.0 million'
>>> intword(1_200_000_000)
'1.2 billion'
>>> intword(8100000000000000000000000000000000)
'8.1 decillion'
>>> intword(None)
'None'
>>> intword("1234000", "%0.3f")
'1.234 million'
```
Args:
value (int, float, str): Integer to convert.
format (str): To change the number of decimal or general format of the number
portion.
Returns:
str: Friendly text representation as a string, unless the value passed could not
be coaxed into an `int`.
"""
try:
if not math.isfinite(float(value)):
return _format_not_finite(float(value))
value = int(value)
except (TypeError, ValueError):
return str(value)
if value < 0:
value *= -1
negative_prefix = "-"
else:
negative_prefix = ""
if value < powers[0]:
return negative_prefix + str(value)
for ordinal_, power in enumerate(powers[1:], 1):
if value < power:
chopped = value / float(powers[ordinal_ - 1])
powers_difference = powers[ordinal_] / powers[ordinal_ - 1]
if float(format % chopped) == powers_difference:
chopped = value / float(powers[ordinal_])
singular, plural = human_powers[ordinal_]
return (
negative_prefix
+ " ".join(
[format, _ngettext(singular, plural, math.ceil(chopped))]
)
) % chopped
singular, plural = human_powers[ordinal_ - 1]
return (
negative_prefix
+ " ".join([format, _ngettext(singular, plural, math.ceil(chopped))])
) % chopped
return negative_prefix + str(value)
def apnumber(value: NumberOrString) -> str:
"""Converts an integer to Associated Press style.
Examples:
```pycon
>>> apnumber(0)
'zero'
>>> apnumber(5)
'five'
>>> apnumber(10)
'10'
>>> apnumber("7")
'seven'
>>> apnumber("foo")
'foo'
>>> apnumber(None)
'None'
```
Args:
value (int, float, str): Integer to convert.
Returns:
str: For numbers 0-9, the number spelled out. Otherwise, the number. This always
returns a string unless the value was not `int`-able, then `str(value)`
is returned.
"""
try:
if not math.isfinite(float(value)):
return _format_not_finite(float(value))
value = int(value)
except (TypeError, ValueError):
return str(value)
if not 0 <= value < 10:
return str(value)
return (
_("zero"),
_("one"),
_("two"),
_("three"),
_("four"),
_("five"),
_("six"),
_("seven"),
_("eight"),
_("nine"),
)[value]
def fractional(value: NumberOrString) -> str:
"""Convert to fractional number.
There will be some cases where one might not want to show ugly decimal places for
floats and decimals.
This function returns a human-readable fractional number in form of fractions and
mixed fractions.
Pass in a string, or a number or a float, and this function returns:
* a string representation of a fraction
* or a whole number
* or a mixed fraction
* or the str output of the value, if it could not be converted
Examples:
```pycon
>>> fractional(0.3)
'3/10'
>>> fractional(1.3)
'1 3/10'
>>> fractional(float(1/3))
'1/3'
>>> fractional(1)
'1'
>>> fractional("ten")
'ten'
>>> fractional(None)
'None'
```
Args:
value (int, float, str): Integer to convert.
Returns:
str: Fractional number as a string.
"""
try:
number = float(value)
if not math.isfinite(number):
return _format_not_finite(number)
except (TypeError, ValueError):
return str(value)
from fractions import Fraction
whole_number = int(number)
frac = Fraction(number - whole_number).limit_denominator(1000)
numerator = frac.numerator
denominator = frac.denominator
if whole_number and not numerator and denominator == 1:
# this means that an integer was passed in
# (or variants of that integer like 1.0000)
return f"{whole_number:.0f}"
if not whole_number:
return f"{numerator:.0f}/{denominator:.0f}"
return f"{whole_number:.0f} {numerator:.0f}/{denominator:.0f}"
def scientific(value: NumberOrString, precision: int = 2) -> str:
"""Return number in string scientific notation z.wq x 10ⁿ.
Examples:
```pycon
>>> scientific(float(0.3))
'3.00 x 10⁻¹'
>>> scientific(int(500))
'5.00 x 10²'
>>> scientific(-1000)
'-1.00 x 10³'
>>> scientific(1000, 1)
'1.0 x 10³'
>>> scientific(1000, 3)
'1.000 x 10³'
>>> scientific("99")
'9.90 x 10¹'
>>> scientific("foo")
'foo'
>>> scientific(None)
'None'
```
Args:
value (int, float, str): Input number.
precision (int): Number of decimal for first part of the number.
Returns:
str: Number in scientific notation z.wq x 10ⁿ.
"""
exponents = {
"0": "⁰",
"1": "¹",
"2": "²",
"3": "³",
"4": "⁴",
"5": "⁵",
"6": "⁶",
"7": "⁷",
"8": "⁸",
"9": "⁹",
"-": "⁻",
}
try:
value = float(value)
if not math.isfinite(value):
return _format_not_finite(value)
except (ValueError, TypeError):
return str(value)
fmt = f"{{:.{str(int(precision))}e}}"
n = fmt.format(value)
part1, part2 = n.split("e")
# Remove redundant leading '+' or '0's (preserving the last '0' for 10⁰).
part2 = re.sub(r"^\+?(\-?)0*(.+)$", r"\1\2", part2)
new_part2 = []
for char in part2:
new_part2.append(exponents[char])
final_str = part1 + " x 10" + "".join(new_part2)
return final_str
def clamp(
value: float,
format: str = "{:}",
floor: float | None = None,
ceil: float | None = None,
floor_token: str = "<",
ceil_token: str = ">",
) -> str:
"""Returns number with the specified format, clamped between floor and ceil.
If the number is larger than ceil or smaller than floor, then the respective limit
will be returned, formatted and prepended with a token specifying as such.
Examples:
```pycon
>>> clamp(123.456)
'123.456'
>>> clamp(0.0001, floor=0.01)
'<0.01'
>>> clamp(0.99, format="{:.0%}", ceil=0.99)
'99%'
>>> clamp(0.999, format="{:.0%}", ceil=0.99)
'>99%'
>>> clamp(1, format=intword, floor=1e6, floor_token="under ")
'under 1.0 million'
>>> clamp(None) is None
True
```
Args:
value (int, float): Input number.
format (str OR callable): Can either be a formatting string, or a callable
function that receives value and returns a string.
floor (int, float): Smallest value before clamping.
ceil (int, float): Largest value before clamping.
floor_token (str): If value is smaller than floor, token will be prepended
to output.
ceil_token (str): If value is larger than ceil, token will be prepended
to output.
Returns:
str: Formatted number. The output is clamped between the indicated floor and
ceil. If the number is larger than ceil or smaller than floor, the output
will be prepended with a token indicating as such.
"""
if value is None:
return None
if not math.isfinite(value):
return _format_not_finite(value)
if floor is not None and value < floor:
value = floor
token = floor_token
elif ceil is not None and value > ceil:
value = ceil
token = ceil_token
else:
token = ""
if isinstance(format, str):
return token + format.format(value)
if callable(format):
return token + format(value)
msg = (
"Invalid format. Must be either a valid formatting string, or a function "
"that accepts value and returns a string."
)
raise ValueError(msg)
def metric(value: float, unit: str = "", precision: int = 3) -> str:
"""Return a value with a metric SI unit-prefix appended.
Examples:
```pycon
>>> metric(1500, "V")
'1.50 kV'
>>> metric(2e8, "W")
'200 MW'
>>> metric(220e-6, "F")
'220 μF'
>>> metric(1e-14, precision=4)
'10.00 f'
```
The unit prefix is always chosen so that non-significant zero digits are required.
i.e. `123,000` will become `123k` instead of `0.123M` and `1,230,000` will become
`1.23M` instead of `1230K`. For numbers that are either too huge or too tiny to
represent without resorting to either leading or trailing zeroes, it falls back to
`scientific()`.
```pycon
>>> metric(1e40)
'1.00 x 10⁴⁰'
```
Args:
value (int, float): Input number.
unit (str): Optional base unit.
precision (int): The number of digits the output should contain.
Returns:
str:
"""
if not math.isfinite(value):
return _format_not_finite(value)
exponent = int(math.floor(math.log10(abs(value)))) if value != 0 else 0
if exponent >= 33 or exponent < -30:
return scientific(value, precision - 1) + unit
value /= 10 ** (exponent // 3 * 3)
if exponent >= 3:
ordinal_ = "kMGTPEZYRQ"[exponent // 3 - 1]
elif exponent < 0:
ordinal_ = "mμnpfazyrq"[(-exponent - 1) // 3]
else:
ordinal_ = ""
value_ = format(value, ".%if" % max(0, precision - (exponent % 3) - 1))
if not (unit or ordinal_) or unit in ("°", "′", "″"):
space = ""
else:
space = " "
return f"{value_}{space}{ordinal_}{unit}"
output/arguments.csv · written by the agent, 20 lines
function,argument,type,required,default
ordinal,value,NumberOrString,yes,
ordinal,gender,str,no,"""male"""
intcomma,value,NumberOrString,yes,
intcomma,ndigits,int | None,no,None
intword,value,NumberOrString,yes,
intword,format,str,no,"""%.1f"""
apnumber,value,NumberOrString,yes,
fractional,value,NumberOrString,yes,
scientific,value,NumberOrString,yes,
scientific,precision,int,no,2
clamp,value,float,yes,
clamp,format,str,no,"""{:}"""
clamp,floor,float | None,no,None
clamp,ceil,float | None,no,None
clamp,floor_token,str,no,"""<"""
clamp,ceil_token,str,no,""">"""
metric,value,float,yes,
metric,unit,str,no,""""""
metric,precision,int,no,3
output/reference.md · written by the agent, 336 lines
# Number humanizing functions (number.py)
This module turns numbers into text that is easier for people to read: ordinals ("3rd"), thousands separators, "1.2 million", Associated Press words, fractions, scientific notation, clamped values and SI-prefixed values. Output uses translation hooks and the locale's thousands and decimal separators, which come from a sibling `i18n` module that is not part of the files provided, so what those return is not documented here.
License: Copyright (c) 2010-2020 Jason Moiron and Contributors. The licence file grants use, copying, modification, merging, publishing, distribution and sublicensing free of charge, provided the copyright and permission notice are kept, and the software is provided "AS IS" without warranty. The file does not state a licence name, and the full text is in `LICENCE.txt`.
Notes that apply to several functions:
- `NumberOrString` is defined in the code as the alias `"float | str"`.
- Where a function says non-finite values are handled, the output is `"NaN"` for not-a-number, `"-Inf"` for negative infinity and `"+Inf"` for positive infinity. These come from a private helper that is not part of the public interface.
- The module also defines the data names `powers` and `human_powers`. They are not functions and are not documented here.
- The code catches only `TypeError` and `ValueError` where it converts a value. An integer too large for `float()` raises `OverflowError`, which is not caught (checked with Python for `float(10**400)` and `math.isfinite(10**400)`; the module itself was not run).
## ordinal
```python
ordinal(value: NumberOrString, gender: str = "male") -> str
```
Converts a number to its ordinal string, such as `1st`, `2nd`, `3rd`, `4th`. Anything `int()` accepts is truncated to an integer first. The suffix comes from a translated table, with 11, 12 and 13 (and numbers ending in them, such as 111) using the "th" entry. A value that cannot be converted is returned as `str(value)`.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `NumberOrString` | yes | | Number to convert. |
| gender | `str` | no | `"male"` | Selects the translation table. The code tests only `gender == "male"`. Any other value, not just `"female"`, uses the female table. The docstring says only "male" or "female" are accepted, but the code does not check this. |
Returns: `str`. The number followed by its suffix. For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"`. If `float(value)` or `int(value)` raises `TypeError` or `ValueError` (for example `None`, a list, or a string such as `"something else"`), it returns `str(value)`.
Errors: none raised for bad input types. `OverflowError` if `value` is an integer too large to convert to float.
Examples:
```pycon
>>> ordinal(1)
'1st'
>>> ordinal(1002)
'1002nd'
>>> ordinal(103)
'103rd'
>>> ordinal(4)
'4th'
>>> ordinal(12)
'12th'
>>> ordinal(101)
'101st'
>>> ordinal(111)
'111th'
>>> ordinal("something else")
'something else'
>>> ordinal([1, 2, 3]) == "[1, 2, 3]"
True
```
## intcomma
```python
intcomma(value: NumberOrString, ndigits: int | None = None) -> str
```
Formats a number with a thousands separator every three digits, for example `3000` becomes `"3,000"`. Floats are accepted. The separators are taken from the locale (`thousands_separator()` and `decimal_separator()`), so a locale other than the default may give different characters. For a string input, the code first removes the thousands separator and turns the decimal separator into `.`. A string containing `.` is then read as a float, otherwise as an int.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `NumberOrString` | yes | | Integer, float or numeric string to format. |
| ndigits | `int \| None` | no | `None` | Digits after the decimal point. When given, the value is formatted with `{:.Nf}`, which rounds. When `None`, the value is converted with `str()`. |
Returns: `str`. The formatted number. For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"`. If the value cannot be converted (`TypeError` or `ValueError` while parsing, for example `None`), it returns `str(value)`.
Errors:
- `OverflowError` if `value` is an integer too large to convert to float.
- `ndigits` is used after the conversion step, outside the code that catches errors. An invalid `ndigits` therefore raises from the formatting call and is not caught. For example, a string `ndigits` raises `ValueError` (checked with Python's `str.format`). This is not mentioned in the docstring.
- Whether a non-numeric `value` that is not a string and not `None` fails or passes through cannot be told from the file alone, apart from what `float()` accepts.
Examples:
```pycon
>>> intcomma(100)
'100'
>>> intcomma("1000")
'1,000'
>>> intcomma(1_000_000)
'1,000,000'
>>> intcomma(1_234_567.25)
'1,234,567.25'
>>> intcomma(1234.5454545, 2)
'1,234.55'
>>> intcomma(14308.40, 1)
'14,308.4'
>>> intcomma("14308.40", 1)
'14,308.4'
>>> intcomma(None)
'None'
```
## intword
```python
intword(value: NumberOrString, format: str = "%.1f") -> str
```
Converts a large number to a short text form such as `"1.2 million"`. The value is first truncated to an integer with `int()`. Negative values are handled by working on the absolute value and putting `-` in front. Values below 1000 are returned as plain digits. The unit names are translated and pluralised from the rounded-up quotient.
Which unit is used, from the code: thousand, million, billion and so on up to decillion are chosen by size, and anything from 10^33 up to below 10^100 is expressed in decillion. Values of 10^100 or more are returned as plain digits. The unit "googol" is listed in the code but can only be selected through the round-up branch (when rounding the number portion would reach the next unit), so the docstring's "googol (100 digits)" is not how the code normally behaves. If the number portion rounds up to the next unit (for example 999999 with `"%.1f"` gives 1000.0), the next unit is used instead.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `NumberOrString` | yes | | Number to convert. |
| format | `str` | no | `"%.1f"` | A `%`-style format applied to the number portion, which is a float. The code also runs `float(format % chopped)` for every value of 1000 or more, so the formatted result must be readable by `float()`. A format that adds other text (for example a literal `%`) fails. The unit word is appended after a space. |
Returns: `str`. The text form. For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"`. If the value cannot be converted, `str(value)`.
Errors:
- `ValueError` if `format % number` is not readable by `float()` (checked: `float('%.1f%%' % 5.0)` raises `ValueError`).
- `TypeError` if `format` has no placeholder that takes a number (checked: `'abc' % 5.0` raises `TypeError`).
- Both only occur for values of 1000 or more, since smaller values never use `format`.
- `OverflowError` if `value` is an integer too large to convert to float.
Examples:
```pycon
>>> intword("100")
'100'
>>> intword("12400")
'12.4 thousand'
>>> intword("1000000")
'1.0 million'
>>> intword(1_200_000_000)
'1.2 billion'
>>> intword(8100000000000000000000000000000000)
'8.1 decillion'
>>> intword(None)
'None'
>>> intword("1234000", "%0.3f")
'1.234 million'
```
## apnumber
```python
apnumber(value: NumberOrString) -> str
```
Converts a number to Associated Press style: 0 to 9 are spelled out (`zero` to `nine`, translated) and anything else is returned as digits. The value is truncated with `int()` first.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `NumberOrString` | yes | | Number to convert. |
Returns: `str`. The spelled-out word when the integer is from 0 to 9 inclusive, otherwise `str()` of the integer (so negative numbers and 10 or more come back as digits). For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"`. If the value cannot be converted, `str(value)`.
Errors: none raised for bad input types. `OverflowError` if `value` is an integer too large to convert to float.
Examples:
```pycon
>>> apnumber(0)
'zero'
>>> apnumber(5)
'five'
>>> apnumber(10)
'10'
>>> apnumber("7")
'seven'
>>> apnumber("foo")
'foo'
>>> apnumber(None)
'None'
```
## fractional
```python
fractional(value: NumberOrString) -> str
```
Converts a number to a fraction, a whole number or a mixed fraction. The value is converted with `float()`. The part after the decimal point is turned into a fraction with the denominator limited to 1000, so the result is an approximation for floats that need a larger denominator.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `NumberOrString` | yes | | Number to convert. |
Returns: `str`, one of:
- a whole number, when the fractional part is zero and the whole part is not zero;
- `numerator/denominator`, when the whole part is zero (code behaviour: `0` gives `"0/1"`, and a value that rounds to 1 within the denominator limit gives `"1/1"`);
- `whole numerator/denominator`, otherwise. The whole part and the fraction are computed separately from the truncated value, so a negative mixed number carries a minus sign on both parts (for example `-1.5` gives `"-1 -1/2"`, by reading the code, not by running it).
For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"`. If the value cannot be converted, `str(value)`.
Errors: none raised for bad input types. `OverflowError` if `value` is an integer too large to convert to float.
Examples:
```pycon
>>> fractional(0.3)
'3/10'
>>> fractional(1.3)
'1 3/10'
>>> fractional(float(1/3))
'1/3'
>>> fractional(1)
'1'
>>> fractional("ten")
'ten'
>>> fractional(None)
'None'
```
## scientific
```python
scientific(value: NumberOrString, precision: int = 2) -> str
```
Returns the number in scientific notation with superscript exponent, in the form `z.wq x 10ⁿ`. The value is converted with `float()`, formatted with `e` notation, and the exponent is rewritten with superscript digits, dropping a leading `+` and leading zeros.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `NumberOrString` | yes | | Number to convert. |
| precision | `int` | no | `2` | Digits after the decimal point in the first part. The code applies `int(precision)`, so a float is truncated. |
Returns: `str`. The notation, for example `"5.00 x 10²"`. For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"`. If `value` cannot be converted, `str(value)`.
Errors:
- A negative `precision` raises `ValueError` ("Format specifier missing precision", checked with Python's `str.format`).
- An invalid `precision` that `int()` rejects raises `TypeError` or `ValueError`. Both happen outside the code that catches errors, so they are not caught.
- `OverflowError` if `value` is an integer too large to convert to float.
Examples:
```pycon
>>> scientific(float(0.3))
'3.00 x 10⁻¹'
>>> scientific(int(500))
'5.00 x 10²'
>>> scientific(-1000)
'-1.00 x 10³'
>>> scientific(1000, 1)
'1.0 x 10³'
>>> scientific(1000, 3)
'1.000 x 10³'
>>> scientific("99")
'9.90 x 10¹'
>>> scientific("foo")
'foo'
>>> scientific(None)
'None'
```
## clamp
```python
clamp(
value: float,
format: str = "{:}",
floor: float | None = None,
ceil: float | None = None,
floor_token: str = "<",
ceil_token: str = ">",
) -> str
```
Formats a number, limiting it to a lower and upper bound. If the value is below `floor`, `floor` is formatted instead and `floor_token` is put in front. If it is above `ceil`, `ceil` is formatted and `ceil_token` is put in front. Otherwise the value is formatted with no token. The floor test is made first.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `float` | yes | | Number to format. `None` is allowed by the code even though the hint says `float`. |
| format | `str` | no | `"{:}"` | A format string, used as `format.format(value)`, or a callable that takes the (possibly clamped) value and returns a string. The type hint says `str` only, but the code also accepts a callable. |
| floor | `float \| None` | no | `None` | Smallest value before clamping. `None` means no lower bound. |
| ceil | `float \| None` | no | `None` | Largest value before clamping. `None` means no upper bound. |
| floor_token | `str` | no | `"<"` | Text put in front when the value is below `floor`. |
| ceil_token | `str` | no | `">"` | Text put in front when the value is above `ceil`. |
Returns: the token plus the formatted value, as `str`. Cases where the result differs from the `str` hint:
- If `value` is `None`, it returns `None`, not a string.
- If `value` is NaN or infinite, it returns `"NaN"`, `"-Inf"` or `"+Inf"` before any clamping, so infinite values are not clamped to `floor` or `ceil`.
- With a callable `format`, the token is added to the callable's result with `+`, so the callable must return a `str`.
Errors:
- `ValueError` if `format` is neither a string nor callable. The message is "Invalid format. Must be either a valid formatting string, or a function that accepts value and returns a string." This is raised after the clamping step.
- `TypeError` if `value` is not a number and not `None` (from the finite check), or if the callable returns something that is not a string.
- Errors raised by `format.format(value)` or by the callable itself are not caught.
Examples:
```pycon
>>> clamp(123.456)
'123.456'
>>> clamp(0.0001, floor=0.01)
'<0.01'
>>> clamp(0.99, format="{:.0%}", ceil=0.99)
'99%'
>>> clamp(0.999, format="{:.0%}", ceil=0.99)
'>99%'
>>> clamp(1, format=intword, floor=1e6, floor_token="under ")
'under 1.0 million'
>>> clamp(None) is None
True
```
## metric
```python
metric(value: float, unit: str = "", precision: int = 3) -> str
```
Returns the value with an SI prefix and an optional unit, for example `1500` with unit `"V"` becomes `"1.50 kV"`. The prefix is chosen from the base-10 exponent of the value in steps of three: `k M G T P E Z Y R Q` for 10^3 up to 10^32, and `m μ n p f a z y r q` for 10^-3 down to 10^-30. If the exponent is 33 or more, or below -30, the code falls back to `scientific(value, precision - 1)` with the unit appended directly, with no space.
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | `float` | yes | | Number to convert. |
| unit | `str` | no | `""` | Base unit appended after the prefix. |
| precision | `int` | no | `3` | Number of significant digits in the output. The decimals shown are `max(0, precision - (exponent % 3) - 1)`. |
Spacing rule from the code: a space separates the number from the prefix and unit, except when there is neither a unit nor a prefix, or when `unit` is one of `°`, `′`, `″`. In those cases there is no space.
Returns: `str`. The docstring's "Returns" entry is empty. The code returns the formatted string. For NaN or infinity, `"NaN"`, `"-Inf"` or `"+Inf"` (without the unit). For a value of `0`, the exponent is taken as 0 and the number is formatted with the precision rule (with the default precision, `"0.00"` by reading the code).
Errors:
- `TypeError` if `value` is not a number (for example `None` or a string), raised by `math.isfinite`. The function does not accept strings, unlike the others.
- `ValueError` in the scientific fallback when `precision - 1` is negative, that is `precision` below 1 (see `scientific`).
- `OverflowError` if `value` is an integer too large to convert to float.
Examples:
```pycon
>>> metric(1500, "V")
'1.50 kV'
>>> metric(2e8, "W")
'200 MW'
>>> metric(220e-6, "F")
'220 μF'
>>> metric(1e-14, precision=4)
'10.00 f'
>>> metric(1e40)
'1.00 x 10⁴⁰'
```
check.py · the check, written before the run
"""Parses the code file itself and compares every function, argument, type, default and example with the reference."""
import ast, csv, re, sys
from pathlib import Path
root = Path(sys.argv[1]); ok = True
def say(passed, text):
global ok; ok = ok and passed; print(("PASS " if passed else "FAIL ") + text)
code = next(p for p in sorted((root/"input").iterdir()) if p.name.endswith(".py.txt")).read_text()
tree = ast.parse(code)
funcs = [n for n in tree.body if isinstance(n, ast.FunctionDef)]
public = [f for f in funcs if not f.name.startswith("_")]
clean = lambda s: re.sub(r"\s+", "", (s or "").strip().strip("`")).replace('"', "'")
want = {}
for f in public:
a = f.args; names = a.posonlyargs + a.args
defaults = [None] * (len(names) - len(a.defaults)) + list(a.defaults)
for arg, d in list(zip(names, defaults)) + list(zip(a.kwonlyargs, a.kw_defaults)):
want[(f.name, arg.arg)] = {"type": clean(ast.unparse(arg.annotation)) if arg.annotation else "",
"required": "yes" if d is None else "no", "default": clean(ast.unparse(d)) if d is not None else ""}
raises = [(f.name, ast.unparse(n.exc.func if isinstance(n.exc, ast.Call) else n.exc)) for f in public
for n in ast.walk(f) if isinstance(n, ast.Raise) and n.exc is not None]
src_lines = [l.strip() for l in code.splitlines()]
pairs = {(src_lines[i], src_lines[i + 1]) for i in range(len(src_lines) - 1) if src_lines[i].startswith(">>> ")}
rp, ap = root/"output/reference.md", root/"output/arguments.csv"
if not rp.exists() or not ap.exists():
say(False, "output/reference.md and output/arguments.csv were not both written"); sys.exit(1)
ref = rp.read_text()
parts = re.split(r"(?m)^## +(.+?)\s*$", ref)
sections = {}
for name, body in zip(parts[1::2], parts[2::2]): sections.setdefault(name.strip().strip("`"), []).append(body)
names = [f.name for f in public]
have = sum(1 for n in names if len(sections.get(n, [])) == 1)
other = [s for s in sections if s not in names]
say(have == len(names) and not other, f"{have} of {len(names)} public functions in the code have their own section in reference.md and {len(other)} sections describe anything else")
rows = list(csv.DictReader(ap.open()))
g = lambda r, k: (r.get(k) or "").strip()
got = {(g(r, "function"), g(r, "argument")): r for r in rows}
listed = sum(1 for k in want if k in got)
say(listed == len(want) and len(rows) == len(want), f"{listed} of {len(want)} arguments in the code are listed in arguments.csv and {len([k for k in got if k not in want])} listed arguments are not in the code")
exact = sum(1 for k, w in want.items() if k in got and clean(g(got[k], "type")) == w["type"]
and g(got[k], "required").lower() == w["required"] and clean(g(got[k], "default")).strip("'") == w["default"].strip("'"))
say(exact == len(want), f"{exact} of {len(want)} arguments carry the type hint, the required flag and the default written in the code")
named = sum(1 for (fn, arg) in want if re.search(r"(?<![\w])" + re.escape(arg) + r"(?![\w])", "".join(sections.get(fn, []))))
say(named == len(want), f"{named} of {len(want)} arguments are described inside the section of their own function")
lines = [l.strip() for l in ref.splitlines()]
ex = [(lines[i], lines[i + 1] if i + 1 < len(lines) else "") for i in range(len(lines)) if lines[i].startswith(">>> ")]
copied = sum(1 for e in ex if e in pairs)
with_ex = sum(1 for n in names if any(l.strip().startswith(">>> ") and n + "(" in l for l in "".join(sections.get(n, [])).splitlines()))
say(bool(ex) and copied == len(ex) and with_ex == len(names), f"{copied} of {len(ex)} example lines are copied from the code with the result the code shows and {with_ex} of {len(names)} functions have an example")
err = sum(1 for fn, exc in raises if exc in "".join(sections.get(fn, [])))
say(bool(raises) and err == len(raises), f"{err} of {len(raises)} errors raised in the code are named in the section of the function that raises them")
# Stricter lines added after the run: the signature shown in each section and the copyright line are compared with the input files.
squash = lambda s: re.sub(r"\s+", "", s).replace('"', "'")
def piece(fn, arg):
w = want[(fn, arg)]
return arg + (":" + w["type"] if w["type"] else "") + ("=" + w["default"] if w["default"] else "")
shown = sum(1 for (fn, arg) in want if piece(fn, arg) in squash("".join(sections.get(fn, []))))
rets = {f.name: squash(ast.unparse(f.returns)) for f in public if f.returns is not None}
ret_ok = sum(1 for fn, r in rets.items() if ")->" + r in squash("".join(sections.get(fn, []))))
say(shown == len(want) and ret_ok == len(rets), f"{shown} of {len(want)} arguments appear in the signature of their section with the type hint and default of the code and {ret_ok} of {len(rets)} return types match")
lic = next((p for p in sorted((root/"input").iterdir()) if p.name.upper().startswith("LICEN")), None)
marks = [" ".join(l.split()) for l in (lic.read_text().splitlines() if lic else []) if l.strip().lower().startswith("copyright")]
kept = sum(1 for m in marks if m in " ".join(ref.split()))
say(bool(marks) and kept == len(marks), f"{kept} of {len(marks)} copyright lines from the license file are repeated word for word in reference.md")
sys.exit(0 if ok else 1)
LICENCE.txt: public document. Fingerprint 8ba6c18112a4.
number.py.txt: public document. Fingerprint e499df8bfe39.
arguments.csv: written by the agent. Fingerprint 4218d60c1442.
reference.md: written by the agent. Fingerprint 919b5fd9674e.