Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gets method information from the docstring
"""
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