Johnny Metz
Johnny Metz

Reputation: 6055

Programmatically get descriptions of python function arguments

Let's say I have the following function:

def get_fullname(first: str, last: str = "Miller"):
    """
    :param first: First name
    :param last: Last name
    :return: Fullname
    """
    return f"{first} {last}"

I know I can get a bunch of information about the function using the inspect module:

import inspect
spec = inspect.getfullargspec(get_fullname)
print(spec)
# FullArgSpec(args=['first', 'last'], varargs=None, varkw=None, defaults=('Miller',), kwonlyargs=[], kwonlydefaults=None, annotations={'first': <class 'str'>, 'last': <class 'str'>})

Is there anyway I can programmatically get the descriptions for these arguments? Doesn't look it's possible but just making sure. Looks like this is a PyCharm way of specifying types.

Upvotes: 5

Views: 471

Answers (2)

Reedinationer
Reedinationer

Reputation: 5774

There is a built in .__doc__ attribute on things like functions and classes too (no installing extra modules). For instance:

def get_fullname(first: str, last: str = "Miller"):
    """
    :param first: First name
    :param last: Last name
    :return: Fullname
    """
    return "{first} {last}"
print(get_fullname.__doc__)

Yields:

    :param first: First name
    :param last: Last name
    :return: Fullname

Not sure if this is what you are intending to find though. This just prints the docstring directly, and doesn't parse it like @blhsing's answer

Upvotes: 0

blhsing
blhsing

Reputation: 107134

You can install and use docstring_parser:

import docstring_parser

def get_fullname(first: str, last: str = "Miller"):
    """
    :param first: First name
    :param last: Last name
    :return: Fullname
    """
    return f"{first} {last}"

doc = docstring_parser.parse(get_fullname.__doc__)
for param in doc.params:
    print(param.arg_name, param.description)
print(doc.returns.description)

This outputs:

first First name
last Last name
Fullname

Upvotes: 3

Related Questions