How do I programmatically set the docstring?

前端 未结 6 1835
慢半拍i
慢半拍i 2020-12-01 07:21

I have a wrapper function that returns a function. Is there a way to programmatically set the docstring of the returned function? If I could write to __doc__ I\

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 07:39

    Just use decorators. Here's your case:

    def add_doc(value):
        def _doc(func):
            func.__doc__ = value
            return func
        return _doc
    
    import unittest
    def makeTestCase(filename, my_func):
        class ATest(unittest.TestCase):
            @add_doc('This should be my docstring')
            def testSomething(self):
                # Running test in here with data in filename and function my_func
                data  = loadmat(filename)
                result = my_func(data)
                self.assertTrue(result > 0)
    
        return ATest
    
    def my_func(): pass
    
    MyTest = makeTestCase('some_filename', my_func)
    print MyTest.testSomething.__doc__
    > 'This should be my docstring'
    

    Here's a similar use case: Python dynamic help and autocomplete generation

提交回复
热议问题