Created
March 12, 2012 17:25
-
-
Save raymondbutcher/2023491 to your computer and use it in GitHub Desktop.
Gets method information from the docstring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Returns this: | |
{ | |
'help_text': 'Returns a list of sites for which the given user has access.', | |
'returns': {'type': 'array', 'desc': 'list of blog dicts'}, | |
'args': { | |
'username': {'type': 'string', 'desc': 'your username'}, | |
'password': {'type': 'string', 'desc': 'plain text password'} | |
} | |
} | |
""" | |
import pydoc | |
import re | |
from django.utils.datastructures import SortedDict | |
def getUsersBlogs(username, password): | |
""" | |
Returns a list of sites for which the given user has access. | |
:param username: your username | |
:type username: string | |
:key password: plain text password | |
:type password: string | |
:returns: list of blog dicts | |
:rtype: array | |
""" | |
return [1, 2, 3] | |
def get_method_info(method): | |
info = {} | |
help_text = pydoc.getdoc(method) | |
args = SortedDict() | |
desc_re = re.compile(':(?P<desc>param|parameter|arg|argument|key|keyword)\s+(?P<name>.+):\s+(?P<value>.+)') | |
type_re = re.compile(':(?P<type>type)\s+(?P<name>.+):\s+(?P<value>.+)') | |
for expression in (desc_re, type_re): | |
for match in expression.finditer(help_text): | |
data = match.groupdict() | |
if 'desc' in data: | |
key = 'desc' | |
else: | |
key = 'type' | |
name = data['name'] | |
value = data['value'] | |
args.setdefault(name, {}) | |
args[name][key] = value | |
help_text = expression.sub('', help_text) | |
if args: | |
info['args'] = args | |
desc_re = re.compile(':(?P<desc>returns?):\s+(?P<value>.+)') | |
type_re = re.compile(':(?P<type>rtype):\s+(?P<value>.+)') | |
for expression in (desc_re, type_re): | |
match = expression.search(help_text) | |
if match: | |
data = match.groupdict() | |
if 'desc' in data: | |
key = 'desc' | |
else: | |
key = 'type' | |
value = data['value'] | |
info.setdefault('returns', {}) | |
info['returns'][key] = value | |
help_text = expression.sub('', help_text) | |
info['help_text'] = help_text.strip() | |
return info | |
print get_method_info(getUsersBlogs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment