1

我编写了以下脚本来加载和分配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()

有没有更蟒蛇的方式来做到这一点?这甚至是个好主意吗? help()即使没有提供正确的元数据,现在也可以打印出来。

也感谢对​​代码的任何评论。

4

1 回答 1

2

pythonic方式(恕我直言)是将文档字符串添加到需要文档的函数、方法和类中,并创建一个标头(在您__init__.py的模块文件中)为您的模块设置其余值。

__author__, __email__, 等仅被定义并用于模块。(见pydoc。)

于 2012-01-10T16:05:22.353 回答