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
398 stars 62 forks source link

Allow file to be used as a contract type #41

Closed textbook closed 9 years ago

textbook commented 9 years ago

Allow file to be used as a contract type within docstrings/text contracts, for example:

@contract
def file_test(in_):
    """Ensure that the file contract works.

   :type in_: file

    """
    return in_.read() 

This should resolve #36.

AndreaCensi commented 9 years ago

I think it could be way simpler than that:

def check_is_file(x):
    return isinstance(x, ...)

new_contract('file', check_is_file)
textbook commented 9 years ago

It certainly makes the code much shorter! But then instead of

ContractNotRespected: Breach for argument 'in_' to file_test().
Expected a file, got 'str'.
checking: file   for value: Instance of str: 'str' 

the user gets:

ContractNotRespected: Breach for argument 'in_' to file_test().
Value does not pass criteria of check_is_file()() (module: ...).
checking: callable()   for value: Instance of str: 'str'   
checking: file    for value: Instance of str: 'str'   
Variables bound in inner context:
- args: Instance of tuple: () 
- kwargs: Instance of dict: {}

I did look into putting it into miscellaneous_aliases, if you think that would be preferable, but it could mean rewriting ist to handle tuples of types for isinstance. Let me know what you think.

AndreaCensi commented 9 years ago

Fair enough --- the error messages are quite cryptic at the moment.

On Tue, Jun 2, 2015 at 8:00 PM, Jonathan Sharpe notifications@github.com wrote:

It certainly makes the code much shorter! But then instead of

ContractNotRespected: Breach for argument 'in_' to file_test(). Expected a file, got 'str'. checking: file for value: Instance of str: 'str'

the user gets

ContractNotRespected: Breach for argument 'in_' to file_test(). Value does not pass criteria of check_is_file()() (module: ...). checking: callable() for value: Instance of str: 'str' checking: filelike for value: Instance of str: 'str' Variables bound in inner context:

  • args: Instance of tuple: ()
  • kwargs: Instance of dict: {}

I did look into putting it into miscellaneous_aliases, if you think that would be preferable, but it could mean rewriting ist to handle tuples of types for isinstance. Let me know what you think.

— Reply to this email directly or view it on GitHub https://github.com/AndreaCensi/contracts/pull/41#issuecomment-108135254.

Andrea Censi | LIDS / MIT | http://censi.mit.edu