0

A Python Boolean Can Pass an Integer Check for Stock Quantity

In Python, isinstance(True, int) is true. If an import accepts only plain nonnegative integer quantities, that broad check accepts a Boolean that the contract did not intend.

In global dropshipping, warehousing and fulfillment messages should state whether quantity is a number, text to parse, or another type. This example intentionally accepts only the built-in int type.

def quantity(value):
    if type(value) is not int or value < 0:
        raise ValueError("plain nonnegative integer required")
    return value

assert isinstance(True, int)
assert quantity(0) == 0
assert quantity(4) == 4
for bad in [True, False, -1, 2.0, "2", None]:
    try:
        quantity(bad)
    except ValueError:
        pass
    else:
        raise AssertionError(repr(bad))
print("9 checks passed")

Python's built-in type documentation describes bool as a subclass of int. Nine checks cover that relationship, accepted zero and positive quantities, and six rejected values.

The exact-type restriction is deliberate and may be unsuitable when another integer type is part of a documented interface. This code also does not impose a business maximum or authorize a stock adjustment. Establish those limits separately. The final code was run locally without real stock, customer records or a live 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.