1. typepy

PyPI package version conda-forge package version Supported Python versions Supported Python implementations Linux/macOS/Windows CI status Test coverage CodeQL

2. Summary

typepy is a Python library for variable type checker/validator/converter at a run time.

3. Features

  • checking a value type
  • validate a value for a type
  • convert a value from one type to the other type

The correspondence between Python types and typepy classes are as follows:

Supported Types
Python Type typepy: Type Class
bool Bool
datetime DateTime
dict Dictionary
float/decimal.Decimal (not infinity/NaN) RealNumber
float/decimal.Decimal (infinity) Infinity
float/decimal.Decimal (NaN) Nan
int Integer
list List
None None
str (not null) String
str (null) NullString
str (IP address) IpAddress

4. Installation

4.1. Installation: pip

pip install typepy

Install additional dependency packages with the following command if using typepy.DateTime class

pip install typepy[datetime]

4.2. Installation: conda

conda install -c conda-forge typepy

4.3. Installation: apt

sudo add-apt-repository ppa:thombashi/ppa
sudo apt update
sudo apt install python3-typepy

5. Dependencies

5.1. Optional dependencies

These packages can be installed via pip install typepy[datetime]:

6. Usage

6.1. Type Check Method

>>> from typepy import Integer
>>> Integer(1).is_type()
>>> Integer(1.1).is_type()

6.2. Type Validation Method

>>> from typepy import Integer
>>> Integer(1).validate()
>>> try:
...     Integer(1.1).validate()
... except TypeError as e:
...     # validate() raised TypeError when the value unmatched the type class
...     print(e)
invalid value type: expected=INTEGER, actual=<type 'float'>

6.3. Type Conversion Methods

6.3.1. convert method

>>> from typepy import Integer, TypeConversionError
>>> Integer("1").convert()
>>> try:
...     Integer(1.1).convert()
... except TypeConversionError as e:
...     # convert() raised TypeConversionError when conversion failed
...     print(e)
failed to convert from float to INTEGER

6.3.2. try_convert method

>>> from typepy import Integer
>>> Integer("1").try_convert()
>>> print(Integer(1.1).try_convert())  # try_convert() returned None when conversion failed

6.3.3. force_convert

>>> from typepy import Integer, TypeConversionError
>>> Integer("1").force_convert()  # force_convert() forcibly convert the value
>>> Integer(1.1).force_convert()
>>> try:
...     Integer("abc").force_convert()
... except TypeConversionError as e:
...     # force_convert() raised TypeConversionError when the value was not convertible
...     print(e)
failed to force_convert to int: type=<class 'str'>

6.4. For more information

Type check/validate/convert results differed according to strict_level value which can pass to typepy class constructors as an argument. More information can be found in the API reference.