Package: valimp
valimpIn Python use type hints to validate, parse and coerce inputs topublic functions and dataclasses.This is the sole use ofvalimp. It's a single short module with no depenencies that does one thing and makes it simple to do.Works like this:fromvalimpimportparse,Parser,CoercefromtypingimportAnnotated,Union,Optional,Any@parse# add the `valimp.parse`` decorator to a public function or methoddefpublic_function(# validate against built-in or custom typesa:str,# support for type unionsb:Union[int,float],# or from Python 3.10 `int | float`# validate type of container itemsc:dict[str,Union[int,float]],# dict[str, int | float]# coerce input to a specific typed:Annotated[Union[int,float,str],# int | float | strCoerce(int)],# parse input with reference to earlier inputs...e:Annotated[str,Parser(lambdaname,obj,params:obj+f"_{name}_{params['a']}")],# coerce and parse input...f:Annotated[Union[str,int],# str | intCoerce(str),Parser(lambdaname,obj,_:obj+f"_{name}")],# support for packing extra arguments if required, can be optionally typed...*args:Annotated[Union[int,float,str],# int | float | strCoerce(int)],# support for optional typesg:Optional[str],# str | None# define default values dynamically with reference to earlier inputsh:Annotated[Optional[float],# float | NoneParser(lambda_,obj,params:params["b"]ifobjisNoneelseobj)]=None,# support for packing excess kwargs if required, can be optionally typed...# **kwargs: Union[int, float])->dict[str,Any]:return{"a":a,"b":b,"c":c,"d":d,"e":e,"f":f,"args",args,"g":g,"h":h}public_function(# NB parameters 'a' through 'f' could be passed positionally"zero",# a1.0,# b{"two":2},# c3.3,# d, will be coerced from float to int, i.e. to 3"four",# e, will be parsed to "four_e_zero"5,# f, will be coerced to str and then parsed to "5_f""10",# extra arg, will be coerced to int and packed20,# extra arg, will be packedg="keyword_arg_g",# h, not passed, will be assigned dynamically as parameter b (i.e. 1.0))returns:{'a': 'zero',
 'b': 1.0,
 'c': {'two': 2},
 'd': 3,
 'e': 'four_e_zero',
 'f': '5_f',
 'args': (10, 20),
 'g': 'keyword_arg_g',
 'h': 1.0}And if there are invalid inputs...public_function(a=["not a string"],# INVALIDb="not an int or a float",# INVALIDc={2:"two"},# INVALID, key not a str and value not an int or floatd=3.2,# valid inpute="valid input",f=5.0,# INVALID, not a str or an intg="valid input",)raises:InputsError: The following inputs to 'public_function' do not conform with the corresponding type annotation:

a
	Takes type <class 'str'> although received '['not a string']' of type <class 'list'>.

b
	Takes input that conforms with <(<class 'int'>, <class 'float'>)> although received 'not an int or a float' of type <class 'str'>.

c
	Takes type <class 'dict'> with keys that conform to the first argument and values that conform to the second argument of <dict[str, typing.Union[int, float]]>, although the received dictionary contains an item with key '2' of type <class 'int'> and value 'two' of type <class 'str'>.

f
	Takes input that conforms with <(<class 'str'>, <class 'int'>)> although received '5.0' of type <class 'float'>.And if the inputs do not match the signature...public_function("zero","invalid input",# invalid (not int or float), included in errors{"two":2},3.2,# no argument passed for required positional arg 'e'# no argument passed for required positional arg 'f'a="a again",# passing multiple values for parameter 'a'# no argument passed for required keyword arg 'g'not_a_kwarg="not a kwarg",# including an unexpected kwarg)raises:InputsError: Inputs to 'public_function' do not conform with the function signature:

Got multiple values for argument: 'a'.

Got unexpected keyword argument: 'not_a_kwarg'.

Missing 2 positional arguments: 'e' and 'f'.

Missing 1 keyword-only argument: 'g'.

The following inputs to 'public_function' do not conform with the corresponding type annotation:

b
	Takes input that conforms with <(<class 'int'>, <class 'float'>)> although received 'invalid input' of type <class 'str'>.Use all the same functionality to validate, parse and coerce the fields of a dataclass...fromvalimpimportparse_clsimportdataclasses@parse_cls# place valimp decorator above the dataclass decorator@dataclasses.dataclassclassADataclass:a:strb:Annotated[Union[str,int],Coerce(str),Parser(lambdaname,obj,params:obj+f"{name}{params['a']}")]rtrn=ADataclass("I'm a and will appear at the end of b",33)dataclasses.asdict(rtrn)output:{'a': "I'm a and will appear at the end of b",
 'b': "33 b I'm a and will appear at the end of b"}Installation$ pip install valimpNo dependencies!Documentationtutorial.ipynboffers a walk-through of all the functionality.Further documentation can be found in the module docstring ofvalimp.py.Why another validation library!?Why even validate input type?Some may argue that validating the type of public inputs is not pythonic and we can 'duck' out of it and let the errors arise where they may. I'd argue that for the sake of adding a decorator I'd rather raise an intelligible error message than have to respond to an issue asking 'why am I getting this error...'.:information_source:valimpis only intended for handling inputs topublic functions and dataclasses. For internal validation, consider using a type checker (for example,mypy).Also, I like the option of abstracting away all parsing, coercion and validation of public inputs and just receiving the formal parameter as required. For example, public methods inmarket-pricesoften include a 'date' parameter. I like to offer users the convenience to pass this as either astr, adatetime.dateor apandas.Timestamp, although internally I want it as apandas.Timestamp. I can do this with Valimp by simply includingCoerce(pandas.Timestamp)to the metadata of the type annotation of each 'date' parameter. I also need to validate that the input is timezone-naive and does indeed represent a date rather than a time. I can do this by defining a singlevalimp.Parserand similarly including it to the annotation metadata of the 'date' parameters. Everything's abstracted away. With a little understanding of type annotations the user can see what's going on by simple inspection of the function's signature (as included within the standard help).Why wouldn't I just use Pydantic?Pydanticis orientated towards the validation of inputs to dataclasses. Whilst the Valimp@parse_clsdecorator does this well for non-complex cases, if you're looking to do more then Pydantic is the place to go.As for validating public function input, in the early releases of Pydantic V2 the@validate_calldecorator failed to provide for validating later parameters based on values received by earlier parameters (aregressionfrom the Pydantic V1@validate_argumentsdecorator). This loss of functionality, together with finding Pydantic somewhat clunky to do anything beyond simple type validation, is what led me to writevalimp. (I believe functionality to validate later parameters based on values receive by earlier parameters may have since been restored in Pydantic V2, see theissue.)In short, if you only want to validate the type of function inputs then Pydantic V2@validate_callwill do the trick. If you're after additional validation, parsing or coercion then chances are you'll findvalimpto be a simpler option.Limitations and Developmentvalimpdoes NOT currently support:Positional-only arguments. Any '/' in the signature (to define
positional-only arguments) will be ignored. Consequently valimp DOES
allow intended positional-only arguments to be passed as keyword
arguments.Validation of subscripted types incollections.abc.Callable(although Valimp will verify that the passed value is callable).valimpcurrently supports:use of the following type annotations:built-in classes, for exampleint,str,list,dictetccustom classescollections.abc.Sequencecollections.abc.Mappingtyping.Anytyping.Literaltyping.Union (|from 3.10 )typing.Optional (<cls> | Nonefrom 3.10)collections.abc.Callable, although validation of subscripted types isnotsupportedvalidation of container items for the following generic classes:listdicttuplesetcollections.abc.Sequencecollections.abc.Mappingpacking and optionally coercing, parsing and validating packed objects, i.e. objects received to, for example, *args and **kwargs.The library has been built with development in mind and PRs are very much welcome!LicenseMIT License