Welcome, guest | Sign In | My Account | Store | Cart

The code below is an example that shows that we can do design by contract in python without any non-standard module.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def function(a, b):
    # description and test
    """Adds an integer and a float and returns a str.
    >>> function(1, 3.0)
    '4.0'
    """

    # precondition
    assert isinstance(a, int), 'a argument should be int'
    assert isinstance(b, float), 'b argument should be float'

    #implementation
    try:
        c = str(a + b)
        return c

    # postcondition
    finally:
        assert isinstance(c, str), 'c variable should be str'


# run all docstring test on debug mode
if __debug__:
    import doctest
    doctest.testmod()


if __name__ == '__main__':
    # do something
    pass

This pattern can be used in function definitions, class definitions, modules and in the same places where you can use documentation strings, try/finally statement and assert statement.

2 comments

Note that this code is not a good example of using assertions. I recommend reading the tutorial When to use assert made ​​by Steven D'Aprano.

Sam Denton 7 years, 11 months ago  # | flag

Did you read the tutorial that you referenced? "assertions should be used for: [...] * checking contracts (e.g. pre-conditions and post-conditions);" I would say that this is a good example of using assertions.