Python Sanity Proposal: Type Hinting Solution

Mario Figueiredo marfig at gmail.com
Sat Jan 24 09:32:55 EST 2015


In article <MPG.2f2dc5f7f281009b98968f at nntp.aioe.org>, marfig at gmail.com 
says...
> 
> In article <54c39e48$0$12996$c3e8da3$5496439d at news.astraweb.com>, 
> steve+comp.lang.python at pearwood.info says...
> > 
> > def myfunction(arg1, arg2):
> >     """
> >     Normal docstring.
> >     @typehint: (str, int) -> bool"""
> >     return True
> > 
> > One of the problems with this is that it put the information about
> > parameters far away from the parameter list itself.
> 
> Then move it to the first line of the docstring...

Here's a more concrete example of what can be done in the docstring, 
taken from one of the examples in PEP 484. (Remember, we just moving the 
whole structure of type hinting to a new docstring parameter, instead of 
having it in the function header.

"PEP 484"
def handle_employees(e: Union[Employee, Sequence[Employee]]):
    if isinstance(e, Employee):
        e = [e]
    ...

"My proposal:"

def handle_employees(e):
    """
    Handles an employee or list of employees by firing the whole
    bunch of 'em lazy sods.

    @hint: Union[Employee, Sequence[Employee]]
    :param e: A single employee or a list of employees 
    :return: None
    """
    if isinstance(e, Employee):
        e = [e]
    ...

If you find that hard to read or feel you still can't match type hints 
to their respective arguments in the function header... then, yeah, 
there's no convincing you.

My only pet peevee with this is that @int: becomes part of __doc__ and 
some pundits may argue against that inclusion. I don't have a real 
answer to that problem. I personally see that as a minor consequence, 
but can understand static analysis isn't really a part of a function 
documentation.



More information about the Python-list mailing list