我编写了以下脚本来加载并为help()
搜索的字段分配默认值:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__ )))
def _get_authors():
path = os.path.dirname(os.path.abspath(__file__ ))
with open('%s\AUTHORS' % path, 'r') as authors:
return ', '.join([author for author in ''.join(authors.readlines()).splitlines()])
def _get_readme():
path = os.path.dirname(os.path.abspath(__file__ ))
with open('%s\README' % path, 'r') as f:
return ''.join(f.readlines())
def _get_copyright():
import datetime
start = 2011
end = datetime.date.today().year
if start == end:
years = str(start)
else:
years = "%d - %d" % (start, end)
return "Copyright %s, %s" % (years, __maintainer__)
__doc__ = _get_readme()
__author__ = _get_authors()
__maintainer__ = "Omer Katz"
__email__ = "omer.drow@gmail.com"
__copyright__ = _get_copyright()
__license__ = "BSD"
__version__ = "0.1.0"
__status__ = "Pre-Alpha"
def _document_api():
def _document(obj):
if not getattr(obj, '__author__', None): setattr(obj, '__author__', __maintainer__)
if not getattr(obj, '__maintainer__', None): setattr(obj, '__maintainer__', __maintainer__)
if not getattr(obj, '__email__', None): setattr(obj, '__email__', __email__)
if not getattr(obj, '__copyright__', None): setattr(obj, '__copyright__', __copyright__)
if not getattr(obj, '__license__', None): setattr(obj, '__license__', __license__)
if not getattr(obj, '__version__', None): setattr(obj, '__version__', __copyright__)
if not getattr(obj, '__status__', None): setattr(obj, '__status__', __license__)
def _document_functions(module):
from inspect import isfunction
functions = [getattr(module, function) for function in dir(module) if isfunction(getattr(module, function)) and function != '_']
for function in functions:
_document(function)
def _document_classes(module):
from inspect import isclass
classes = [getattr(module, klass) for klass in dir(module) if isclass(getattr(module, klass)) and klass != '_']
for klass in classes:
_document_functions(klass)
_document(klass)
from pkgutil import walk_packages
from django.utils.importlib import import_module
packages = [package for _, package, __ in walk_packages([os.path.dirname(os.path.abspath(__file__ ))])]
for package in packages:
module = import_module('hammerhead.%s' % package)
_document_functions(module)
_document_classes(module)
_document(module)
_document_api()
有更多的pythonic方式吗?
这甚至是个好主意吗?
help()
现在可以打印出正确的元数据,即使没有提供也是如此。
对代码的任何评论也表示赞赏。
答案 0 :(得分:2)
pythonic方式(imho)将文档字符串添加到需要文档的函数,方法和类中,并创建一个标题(在模块的__init__.py
文件中),用于设置其余的值你的模块。
__author__
,__email__
等仅定义并用于模块。 (见pydoc。)