python3: doctest helper/internal functions?

两盒软妹~` 提交于 2020-07-23 11:51:06

问题


How do I make the following work so that helpers's test is run? It doesen't.

def B():
    def helper():
        """
        >>> some doctest
        result
        """

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

回答1:


Nested functions cannot be found, because the function object doesn't exist until the B() function is run. You'd have to return it as the result of calling the B() function, then assign it to the __test__ dictionary:

def B()
    def helper()
        """
        >>> some doctest
        result
        """

    return helper    

# ...

if __name__ == "__main__":
    import doctest
    __test__ = {'helper': B()}
    doctest.testmod() 

doctest.testmod() looks for the __test__ global dictionary and looks for docstrings on any classes, methods, functions and modules in the values; any string values are directly executed as docstring tests.

If B() does other things besides, then you probably should make helper() a simple global function instead:

def B():
    # uses helper

def helper()
    """
    >>> some doctest
    result
    """

# ...

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


来源:https://stackoverflow.com/questions/29307730/python3-doctest-helper-internal-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!