typepy: Runtime Type Checker, Validator, and Converter
typepy is a Python library for variable type checking, validation, and conversion at runtime. As of version 1.3.4, it supports Python 3.9 and newer. It maintains an active release cadence, with several minor updates per year addressing compatibility, new Python versions, and bug fixes.
Warnings
- breaking Support for Python 3.7 and 3.8 was dropped in version 1.3.3. Ensure your environment uses Python 3.9 or newer.
- breaking The `Binary` type class was renamed to `Bytes` in version 1.1.0 to align with Python 3's `bytes` type. Usage of `Binary` will result in an `AttributeError`.
- breaking Support for Python 3.6 was dropped in version 1.3.1. `typepy` now requires Python 3.7 (or later, as of 1.3.3).
- gotcha When performing type conversions, `convert()` will raise a `typepy.TypeConversionError` on failure, while `try_get()` allows specifying a `default_value` to return instead of raising an error.
Install
-
pip install typepy
Imports
- Type
import typepy tc = typepy.Type(...)
- String
from typepy import String s = String(' value ') - Integer
from typepy import Integer i = Integer('123') - DateTime
from typepy import DateTime dt = DateTime('2023-01-01')
Quickstart
import typepy
# Generic type checking and conversion
tc = typepy.Type('100')
print(f"Converted '100' to integer: {tc.try_get(typepy.Type.INTEGER)}")
tc_none = typepy.Type(None)
print(f"Converted None to string with default: {tc_none.try_get(typepy.Type.STRING, default_value='a')}")
# Using specific type classes
str_value = typepy.String(' hello ').strip()
print(f"Stripped string: '{str_value}'")
int_value = typepy.Integer('1,234').convert()
print(f"Converted '1,234' to integer: {int_value}")
try:
# Conversion without try_get will raise an error on failure
invalid_int = typepy.Integer('abc').convert()
print(f"Converted 'abc' to integer: {invalid_int}")
except typepy.TypeConversionError as e:
print(f"Error converting 'abc' to integer: {e}")