Skip to content

fix(PythonCodeTableWriter): emit float("-inf") for negative infinity#81

Open
gaoflow wants to merge 1 commit into
thombashi:masterfrom
gaoflow:fix/python-writer-negative-infinity
Open

fix(PythonCodeTableWriter): emit float("-inf") for negative infinity#81
gaoflow wants to merge 1 commit into
thombashi:masterfrom
gaoflow:fix/python-writer-negative-infinity

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 25, 2026

Copy link
Copy Markdown

Problem

PythonCodeTableWriter renders float("-inf") (negative infinity) as
float("inf") — valid Python syntax but the wrong value, silently
producing positive infinity when the generated code is executed.

import math, pytablewriter

writer = pytablewriter.PythonCodeTableWriter()
writer.table_name = "data"
writer.headers = ["val"]
writer.value_matrix = [[-math.inf], [math.inf]]
print(writer.dumps())

Before this fix:

data = [
    ["val"],
    [float("inf")],   # ← should be float("-inf")
    [float("inf")],
]

Root cause

dataproperty normalises every infinity value to Decimal('Infinity')
before type_value_map is applied, losing the sign. Both math.inf
and -math.inf therefore hit the same map entry
{Typecode.INFINITY: 'float("inf")'}.

Fix

Override _to_row_item in PythonCodeTableWriter to check the
original value in value_matrix when the mapped literal is
float("inf"). If the original was a negative-infinity float,
substitute float("-inf") instead.

After this fix

data = [
    ["val"],
    [float("-inf")],  # ✓ correct
    [float("inf")],   # ✓ correct
]

Tests

Added a parametrised test case covering -inf, +inf, and nan to
test/writer/text/sourcecode/test_python_code_writer.py.


This pull request was prepared with the assistance of AI, under my direction and review.

dataproperty normalises every infinity value to Decimal('Infinity'),
losing the sign before the type_value_map substitution runs.
As a result, -inf was rendered as float("inf") — valid syntax but
the wrong value — producing Python code that silently evaluates to
positive infinity.

Override _to_row_item to detect when the original value in
value_matrix is a negative infinity float and substitute the correct
float("-inf") literal.

Add a parametrised test case covering -inf, +inf, and nan.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant