Skip to content

Instantly share code, notes, and snippets.

@gvx
Created March 5, 2011 23:03
Show Gist options
  • Save gvx/856810 to your computer and use it in GitHub Desktop.
Save gvx/856810 to your computer and use it in GitHub Desktop.
A simple test of annotations, generating extended docstrings
def doc(f):
newdoc = f.__doc__ and [f.__doc__, ''] or []
c = f.__code__
ann = f.__annotations__
max_i = c.co_argcount + c.co_kwonlyargcount
for arg_index in range(max_i):
name = c.co_varnames[arg_index]
if name in ann:
newdoc.append(name + ': ' + str(ann[name]))
else:
newdoc.append(name)
if c.co_flags & 4:
name = c.co_varnames[max_i]
if name in ann:
newdoc.append('*' + name + ': ' + str(ann[name]))
else:
newdoc.append('*' + name)
max_i += 1
if c.co_flags & 8:
name = c.co_varnames[max_i]
if name in ann:
newdoc.append('**' + name + ': ' + str(ann[name]))
else:
newdoc.append('**' + name)
if 'return' in ann:
if newdoc and newdoc[-1]:
newdoc.append('')
newdoc.append('Returns ' + ann['return'])
f.__doc__ = '\n'.join(newdoc)
return f
@doc
def do_something(a: "the first number", b: "the second number", *args: "other arguments") -> "the fudge of a and b":
"""Number fudger"""
return a*b - a - b
print(do_something.__doc__)
# prints:
# Number fudger
#
# a: the first number
# b: the second number
# *args: other arguments
#
# Returns the fudge of a and b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment