I have written the following script to load and assign the default values for the fields that help()
searches for:
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()
Is there a more pythonic way to do it?
Is it even a good idea?
help()
will now be able to print out the correct metadata even if it is not provided.
Any comments on the code are also appreciated.
The pythonic way (imho) would be to add docstrings to functions, methods and classes that need documentation, and create a single header (in your __init__.py
file for the module) that sets the rest of those values for your module.
__author__
, __email__
, etc are only defined and used for modules anyways. (See pydoc.)