Skip to content
Accept integer counts without truncation using operator.index

Accept integer counts without truncation using operator.index

November 22, 2026

A count parameter should not quietly turn 3.9 into three. The integer-index protocol lets a function accept integer-like objects while rejecting ordinary floats and strings.

Run the example

Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Save this as demo_python_operator_index_count_validation.py. Use that filename to avoid shadowing a standard-library module.

from operator import index

class BatchSize:
    def __index__(self):
        return 4

def checked_count(value):
    if isinstance(value, bool):
        raise TypeError("booleans are not counts")
    result = index(value)
    if result < 0:
        raise ValueError("count must be nonnegative")
    return result

for label, value in (("integer", 3), ("protocol", BatchSize()),
                     ("float", 3.9), ("text", "3"),
                     ("boolean", True), ("negative", -1)):
    try:
        print(f"{label}: {checked_count(value)}")
    except (TypeError, ValueError) as error:
        print(f"{label}: {type(error).__name__}")

Run it:

python3 demo_python_operator_index_count_validation.py

Output:

integer: 3
protocol: 4
float: TypeError
text: TypeError
boolean: TypeError
negative: ValueError

The custom object supplies __index__, so it participates in the same count validation as an integer. Float and text conversion remain outside this boundary. Booleans need an explicit rejection because they otherwise behave as integer values in Python.

Input policy and limits

A nonnegative count can still be too large for a buffer or job. Add a domain-specific maximum before allocating resources. Calling a user-defined protocol method executes that object’s code; this is a type contract for objects in your program, not a sandbox for untrusted code.

Clean up

In the same Bash session, remove the source file and the empty working directory:

rm -- demo_python_operator_index_count_validation.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its contents before deleting anything else.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on