Introduction

Python is strongly, dynamically typed. This is fine, but at times when objects get too complicated, it can be a good thing to check for types.

Checktype allows simple checking of Python object formats. It has a very intuitive type system that mimics the way you define your own Python objects.

It can be particularily helpful when refactoring programs. Its performance has not been optimized and it is intended as a development-time type checking utility (disabled by default, and should probably be activated in tests only).

Related

Installation

You can install checktype with pip:

pip install checktype

Usage examples:

fromchecktypeimportchecktype,activate_checktype,check# 'activates' checktype. You need to explicitly call this,# else it will do nothing (by default, to save cpu time).# It is common to specify it in testsactivate_checktype()# checktype only provides a single function, that takes two arguments.# the first one is the python object you want to test;# the second one is an 'object specification' (spec), that mimics the way# objects are represented in Python. This spec is a string representation of# a python object. For example, to check that 12 is an int or 'hello' is a str:checktype(12,'int')checktype('hello','str')# A list of exactly 3 floats is specified as [float,float,float]checktype([1.0,2.0,3.0],'[float,float,float]')# To match a variable-length list of ints, use [int..]checktype([1,2,3],'[int..]')# To only check that it is a list (but not its content), use []checktype([1,"deux"],'[]')# And so on for tuples,checktype((1,2,3),'(int,int,int)')checktype((1,2,3),'(int..)')checktype((1,"deux"),'()')# dictionnaries,checktype({11:2,12:3},'{int:int}')checktype({11:2,12:3},'{}')# and sets.checktype({11,2},'{int}')# Use the ? wildcard if you don't want to check for a specific partchecktype({11:2,12:"a",13:(3,4)},'{int:?}')# Further exampleschecktype({11:(2,3),12:(4,"5")},'{ int: (int,?)}')checktype([(2,"asdf"),(-12,"asfwe"),(1,"")],"[(int,str)..]")checktype([(1,'hello',2.0)],"[(int, str, float)]")# Decorator examples@check("str.. -> int")deffn_1(a1,a2):return1fn_1("say","hello")@check("str, {str:int} -> [int..]")deffn_3(a1,a2):return[1,2,3]fn_3("say",{"hello":1})