问题描述
我有一个返回函数的包装函数.有没有办法以编程方式设置返回函数的文档字符串?如果我可以写信给 __doc__
,我会执行以下操作:
def 包装器(a):def add_something(b):返回 a + badd_something.__doc__ = '将 ' + str(a) + ' 添加到 `b`'返回 add_something
那我就可以了
>>>add_three = 包装器(3)>>>add_three.__doc__'将 3 添加到 `b`但是,由于 __doc__
是只读的,我不能这样做.正确的做法是什么?
好的,我想保持简单,但这当然不是我真正想要做的.尽管通常 __doc__
在我的情况下是可写的,但它不是.
我正在尝试自动为 unittest
创建测试用例.我有一个包装函数,它创建一个类对象,它是 unittest.TestCase
的子类:
导入单元测试def makeTestCase(文件名,my_func):类 ATest(unittest.TestCase):def testSomething(自我):# 使用文件名中的数据和函数 my_func 在此处运行测试数据 = loadmat(文件名)结果 = my_func(data)self.assertTrue(结果> 0)返回 ATest
如果我创建这个类并尝试设置 testSomething
的文档字符串,我会收到一个错误:
我会将文档字符串传递给工厂函数并使用 type
手动构造类.
def make_testcase(filename, myfunc, docstring):def test_something(self):数据 = loadmat(文件名)结果 = myfunc(数据)self.assertTrue(结果> 0)clsdict = {'test_something': test_something,'__doc__':文档字符串}返回类型('ATest',(unittest.TestCase,),clsdict)MyTest = makeTestCase('some_filename', my_func, '这是一个文档字符串')
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'd do the following:
def wrapper(a):
def add_something(b):
return a + b
add_something.__doc__ = 'Adds ' + str(a) + ' to `b`'
return add_something
Then I could do
>>> add_three = wrapper(3)
>>> add_three.__doc__
'Adds 3 to `b`
However, since __doc__
is read-only, I can't do that. What's the correct way?
Edit: Ok, I wanted to keep this simple, but of course this is not what I'm actually trying to do. Even though in general __doc__
is writeable in my case it isn't.
I am trying to create testcases for unittest
automatically. I have a wrapper function that creates a class object that is a subclass of 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
If I create this class and try to set the docstring of testSomething
I get an error:
>>> 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
I would pass the docstring into the factory function and use type
to manually construct the class.
def make_testcase(filename, myfunc, docstring):
def test_something(self):
data = loadmat(filename)
result = myfunc(data)
self.assertTrue(result > 0)
clsdict = {'test_something': test_something,
'__doc__': docstring}
return type('ATest', (unittest.TestCase,), clsdict)
MyTest = makeTestCase('some_filename', my_func, 'This is a docstring')
这篇关于如何以编程方式设置文档字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!