Python3 my tips. コールバック関数で四則演算とテスト。callback function, doctest, testmod()

Python3 コード

my_callback_func.py

#!/usr/bin/env python3


"""(docstring)
"""


def apply_async(my_func, args, *, callback):
    """(docstring)
    """

    res = my_func(*args)
    callback(res)


def print_res(res):
    """(docstring)

    doctest:
    >>> apply_async(add_func, (2, 3), callback=print_res)
    res: 5
    >>> apply_async(sub_func, (4, 5), callback=print_res)
    res: -1
    >>> apply_async(multi_func, (6, 7), callback=print_res)
    res: 42
    >>> apply_async(div_func, (8, 2), callback=print_res)
    res: 4.0
    >>> apply_async(div_func, (9, 0), callback=print_res)
    res: 0? Why so?
    """

    print('{0}{1}'.format('res: ', res))


def add_func(x, y):
    """(docstring)
    """

    return x+y


def sub_func(x, y):
    """(docstring)
    """

    return x-y


def multi_func(x, y):
    """(docstring)
    """

    return x*y


def div_func(x, y):
    """(docstring)
    """

    if y == 0:
        return '0? Why so?'

    return x/y


if __name__ == '__main__':
    import doctest
    doctest.testmod()

    apply_async(add_func, (2, 3), callback=print_res)
    apply_async(sub_func, (4, 5), callback=print_res)
    apply_async(multi_func, (6, 7), callback=print_res)
    apply_async(div_func, (8, 2), callback=print_res)
    apply_async(div_func, (9, 0), callback=print_res)

出力

とくにテスト結果を見る必要がなければ、-v オプションは不要。

以下では、-v オプションをつけて出力している。

$ python3 my_callback_func.py -v
Trying:
    apply_async(add_func, (2, 3), callback=print_res)
Expecting:
    res: 5
ok
Trying:
    apply_async(sub_func, (4, 5), callback=print_res)
Expecting:
    res: -1
ok
Trying:
    apply_async(multi_func, (6, 7), callback=print_res)
Expecting:
    res: 42
ok
Trying:
    apply_async(div_func, (8, 2), callback=print_res)
Expecting:
    res: 4.0
ok
Trying:
    apply_async(div_func, (9, 0), callback=print_res)
Expecting:
    res: 0? Why so?
ok
6 items had no tests:
    __main__
    __main__.add_func
    __main__.apply_async
    __main__.div_func
    __main__.multi_func
    __main__.sub_func
1 items passed all tests:
   5 tests in __main__.print_res
5 tests in 7 items.
5 passed and 0 failed.
Test passed.
res: 5
res: -1
res: 42
res: 4.0
res: 0? Why so?