所以我正在尝试创建一个"动态"文档字符串,如下所示:
ANIMAL_TYPES = ["mammals", "reptiles", "other"]
def func(animalType):
""" This is a sample function.
@param animalType: "It takes one of these animal types %s" % ANIMAL_TYPES
"""
Run Code Online (Sandbox Code Playgroud)
基本上让文档字符串@param animalType显示任何ANIMAL_TYPES有; 这样当更新此变量时,docstring将自动更新.
然而不幸的是,它似乎没有用......有谁知道是否有办法实现这一目标?
sen*_*rle 43
一种方法是使用装饰器.我不确定我对此感觉如何; 我实际上搜索了这个方法的评论,并找到了这个答案,正确地指出它可以掩盖一个设计问题.但是你的用例乍一看对我来说似乎很合理.
无论如何,这是一种相当优雅的方式来实现您正在寻找的结果:
>>> def docstring_parameter(*sub):
... def dec(obj):
... obj.__doc__ = obj.__doc__.format(*sub)
... return obj
... return dec
...
>>> @docstring_parameter('Ocean')
... def foo():
... '''My Docstring Lies Over The {0}'''
... pass
...
>>> @docstring_parameter('Sea')
... def bar():
... '''My Docstring Lies Over The {0}'''
... pass
...
>>> @docstring_parameter('Docstring', 'Me')
... def baz():
... '''Oh Bring Back My {0} To {1}'''
... pass
...
>>> foo.__doc__
'My Docstring Lies Over The Ocean'
>>> bar.__doc__
'My Docstring Lies Over The Sea'
>>> foo.__doc__
'My Docstring Lies Over The Ocean'
>>> baz.__doc__
'Oh Bring Back My Docstring To Me'
Run Code Online (Sandbox Code Playgroud)
Chr*_*gan 18
三引号字符串是一个大字符串.在他们内部没有任何评估.该%部分是字符串的所有部分.你需要让它在实际的字符串上运行.
def func(animalType):
"""
This is a sample function.
@param animalType: "It takes one of these animal types %(ANIMAL_TYPES)s"
""" % {'ANIMAL_TYPES': ANIMAL_TYPES}
Run Code Online (Sandbox Code Playgroud)
不过,我不确定这是否会正常工作; docstrings有点神奇.
这将不工作; docstring在编译时被评估(作为函数中的第一个语句,因为它是一个字符串文字 - 一旦它得到了%它不仅仅是一个字符串文字),字符串格式化在运行时发生,所以__doc__将为空:
>>> def a(): 'docstring works'
...
>>> a.__doc__
'docstring works'
>>> def b(): "formatted docstring doesn't work %s" % ':-('
...
>>> b.__doc__
>>>
Run Code Online (Sandbox Code Playgroud)
如果您想以这种方式工作,则需要func.__doc__ %= {'ANIMAL_TYPES': ANIMAL_TYPES}在定义函数后执行此操作.请注意,python -OO如果您没有检查__doc__已定义的内容,那么这将会破坏,如-OO条带docstrings.
>>> def c(): "formatted docstring works %s"
...
>>> c.__doc__
"formatted docstring works %s"
>>> c.__doc__ %= 'after'
>>> c.__doc__
"formatted docstring works after"
Run Code Online (Sandbox Code Playgroud)
这不是标准技术; 标准技术是引用适当的常量:"采用ANIMAL_TYPES中的一种动物类型"或类似方法.
您还可以使用定义文档字符串 .__doc__
例如:
>>> def f():
pass
>>> x = 1
>>> y = "docstring"
>>> f.__doc__ = "%s string %s" % (x, y)
>>> print(f.__doc__)
1 string docstring
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16856 次 |
| 最近记录: |