我有一个包装器函数,它返回一个函数。是否有方法以编程方式设置返回函数的docstring?如果我能给__doc__
写信,我会做以下事情:
def wrapper(a):
def add_something(b):
return a + b
add_something.__doc__ = 'Adds ' + str(a) + ' to `b`'
return add_something
那我就可以了
>>> add_three = wrapper(3)
>>> add_three.__doc__
'Adds 3 to `b`
但是,由于__doc__
是只读的,所以我不能这样做。正确的方法是什么?
编辑:好吧,我想保持简单,但这当然不是我真正想做的。尽管一般来说__doc__
在我的情况下是可写的,但它不是
我正在尝试为unittest
自动创建测试用例。我有一个包装器函数,它创建一个类对象,它是unittest.TestCase
的子类:
import unittest
def makeTestCase(filename, my_func):
class ATest(unittest.TestCase):
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
如果我创建这个类并尝试设置testSomething
的docstring,就会得到一个错误:
>>> def my_func(): pass
>>> MyTest = makeTestCase('some_filename', my_func)
>>> MyTest.testSomething.__doc__ = 'This should be my docstring'
AttributeError: attribute '__doc__' of 'instancemethod' objects is not writable
我将docstring传递到factory函数中,并使用
type
手动构造类。就用装饰工吧。这是你的箱子:
这里有一个类似的用例:Python dynamic help and autocomplete generation
instancemethod
从其__func__
中获取其docstring。改为更改__func__
的docstring。(函数的__doc__
属性是可写的。)从2.7 docs:
相关问题 更多 >
编程相关推荐