pythonic方法是什么来指定要由help()打印的默认值?

2024-04-26 17:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有没有更像Python的方法? 这是个好主意吗? help()现在可以打印出正确的元数据,即使没有提供元数据。在

如有任何意见,我们也将不胜感激。在


Tags: pathinimportnoneobjforifos
1条回答
网友
1楼 · 发布于 2024-04-26 17:50:39

pythonic方法(imho)是将docstring添加到需要文档的函数、方法和类中,并创建一个单独的头(在模块的__init__.py文件中),为模块设置其余的值。在

__author____email__等仅定义并用于模块。(见pydoc。)

相关问题 更多 >