0

A Decimal Weight Still Needs a Finite-Value Check

Decimal avoids some binary floating-point surprises, but constructing a Decimal does not establish that a parcel weight is a usable positive finite number. It can represent NaN and infinity.

In global dropshipping tooling, warehousing and fulfillment records may carry weight as text. Check the value before a comparison, not only whether parsing raised an exception.

Reject special values before comparing

The order matters: is_finite() is checked first. A NaN should not reach the positive-weight comparison. The function below accepts numeric text and returns a Decimal without changing its units.

from decimal import Decimal, InvalidOperation

def positive_weight(text):
    if not isinstance(text, str) or not text.strip():
        raise ValueError("weight must be text")
    try:
        value = Decimal(text)
    except InvalidOperation as exc:
        raise ValueError("invalid weight") from exc
    if not value.is_finite() or value <= 0:
        raise ValueError("positive finite weight required")
    return value

assert positive_weight("1.25") == Decimal("1.25")
assert positive_weight(" 2 ") == Decimal(2)
assert positive_weight("1e2") == Decimal(100)
for text in ["NaN", "sNaN", "Infinity", "-Infinity", "0", "-1", "", "oops"]:
    try:
        positive_weight(text)
    except ValueError:
        pass
    else:
        raise AssertionError("bad weight accepted")
print("11 checks passed")

What the local run covers

The eleven acceptance or rejection cases include ordinary decimals, surrounding whitespace, exponent notation, NaN, signalling NaN, both infinities, zero, a negative value, empty text and invalid text. The example uses no carrier, store or production system.

What remains outside this function

This deliberately permits exponent notation and whitespace. If the file contract requires a stricter lexical form, validate that too. Agree kilograms or grams separately and enforce realistic upper bounds, decimal precision and file size. A positive finite number can still be the wrong product weight or use the wrong unit.

The Python Decimal documentation describes special values and is_finite(). This is a small value-validation example, not a tested shipping quote integration.

Computer workstations and printing equipment in a warehouse.

Computer workstations and printing equipment in a warehouse.


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.