Skip to content

Instantly share code, notes, and snippets.

View whoschek's full-sized avatar

Wolfgang Hoschek whoschek

View GitHub Profile
@dmitriykovalev
dmitriykovalev / python-argparse-check-range.md
Last active November 23, 2025 20:44
CheckRange class for the Python argparse module

Python: CheckRange for argparse

The Python argparse module lacks a built-in mechanism for validating argument ranges. For instance, while you can specify an argument type as int, there is no straightforward way to restrict it to only positive values. Similarly, when dealing with float arguments, there is no native method to ensure that the provided values fall within the range of [0.0, 1.0).

CheckRange is a possible solution to this problem. It is a subclass of argparse.Action. It allows you to validate open, closed, and half-open intervals. Each endpoint can be either a number or positive or negative infinity:

  • [a, b] → min=a, max=b