Skip to content

loads() inconsistently handles 'Infinity' and 'NaN' — returns strings instead of floats #20

@anthonyoteri

Description

@anthonyoteri

Bug

loads() uses json.loads(token) to coerce bare scalar tokens to native Python types. This correctly converts 42int, 3.14float, truebool, nullNone. However, json.loads rejects Infinity, -Infinity, and NaN with a ValueError, causing them to fall back to plain strings — inconsistent with numeric tokens of the same conceptual type.

Reproducer

import structprop

data = structprop.loads("x = Infinity\ny = NaN\nz = 3.14\n")
print(type(data["x"]))  # <class 'str'>   — unexpected
print(type(data["y"]))  # <class 'str'>   — unexpected
print(type(data["z"]))  # <class 'float'> — expected

Expected behaviour

Infinity, -Infinity, and NaN should deserialize as float('inf'), float('-inf'), and float('nan') respectively, consistent with how other numeric literals are handled.

Suggested fix

Catch the ValueError from json.loads and attempt float(token) as a fallback before returning the token as a plain string:

try:
    return json.loads(token)
except ValueError:
    try:
        return float(token)
    except ValueError:
        return token

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions