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

contracts on class structure #59

Open asmodehn opened 7 years ago

asmodehn commented 7 years ago

It would be helpful to check custom types.

For example if an instance of a class is defined as such :

class CustomClass(object):
    class_member = 42
    def __init__(self):
        inst_member = 23

cc_inst = CustomClass()

It would be useful to have a contract for a function that require such an instance. To keep python duck-typing semantic, we can check the instance members (just like we do for dict), but checking one by one :

@contract("object(class_member: int, inst_member: int)")
def process_custom(custom_class_instance):
    [...]

This way any object that has an int class_member and an int inst_member will satisfy the contract.

I am posting this issue because I haven't found any way to do this currently...

AndreaCensi commented 6 years ago

[deleted]

Sorry, I misunderstood what you meant. Yes, this would be a useful thing to have.