AndreaCensi / contracts

PyContracts is a Python package that allows to declare constraints on function parameters and return values. Contracts can be specified using Python3 annotations, or inside a docstring. PyContracts supports a basic type system, variables binding, arithmetic constraints, and has several specialized contracts and an extension API.
http://andreacensi.github.io/contracts/
Other
399 stars 61 forks source link

Map functionality for collection types #18

Closed szaydel closed 10 years ago

szaydel commented 10 years ago

I also noticed, and maybe I am wrong, that I cannot easily apply a custom validation function over all objects of a collection, be they a dict or list. This may be something that others will find useful as well. For example, maybe I want to validate that all items in a list are only alpha-numeric, have at most 2 numerals and say are no longer than 30 chars.

Anyway, sounds esoteric, but I have use for this today.

AndreaCensi commented 10 years ago

Can be done like this:

@new_contract
 def my_condition(x):
      return x > 0

 @contract(a='list(my_condition)')
 def f(a):
      pass
szaydel commented 10 years ago

Could you give an example of what this would look like in a docstring. I was trying with something very similar to this in a docstring, but I guess there must have been something wrong. Thank you!

AndreaCensi commented 10 years ago

See if this helps:

https://github.com/AndreaCensi/contracts/blob/master/demos/custom_conds_in_docstrings.py

szaydel commented 10 years ago

@AndreaCensi Yes, this is definitely looking like what I want exactly. I must have been doing something wrong when I was plying with docstrings. I had what I thought looked just like this. Anyway, I need to try again and see if that indeed is what I did before. Thanks a lot!

AndreaCensi commented 10 years ago

No problem!