iotile / typedargs

API typechecking and command line shell generation package
GNU Lesser General Public License v3.0
1 stars 2 forks source link

Support function annotations in @docannotate #59

Closed timburke closed 4 years ago

timburke commented 4 years ago

The modern way to indicate that a python function is suitable for calling directly from the command line is by applying an @docannotate decorator to it.

This parses the docstring of the function, assuming that it is formatted in a Pep8 compatible way with google-style docstring stanzas and pulling out the type information from the Args and Returns stanzas.

However, if the function is also annotated with type annotations on the parameters and return value, we should pull the type information from the annotations rather than requiring the user to duplicate it into the docstring. For cases where there are not function annotations, we need to still support pulling the info from the docstring.

For speed of cli startup, we should defer actual parsing until the first time the function is called like docannotate currently does.

As a test-case, the following two functions should result in equivalent annotations:

def func1(action: str, flag: bool = True) -> str:
    """Do a thing.

    Args:
        action: The thing to do
        flag: An optional flag controlling the action

    Returns:
        The result of the action.
    """
def func2(action, flag=True):
    """Do a thing.

    Args:
        action (str): The thing to do
        flag (bool): An optional flag controlling the action

    Returns:
        str: The result of the action.
    """

If both function annotations and docstring types are present, the function annotation should win and a warning should be printed once at parse time saying there's a mismatch.