Python Sanity Proposal: Type Hinting Solution

Mario Figueiredo marfig at gmail.com
Fri Jan 23 17:42:36 EST 2015


In article <4b3b498a-c9b0-443d-8514-87ccd8e98f43 at googlegroups.com>, 
rantingrickjohnson at gmail.com says...
> 
>     (Example modified for PEP8 compliance ;-)
> 
>     @typehint(arg1:str, arg2:int, returns:bool)
>     def myfunction(arg1, arg2): 
>         return True 
>         
> Of course "@typehint" could be an extension of the decorator
> syntax, a keyword, a build-in function or whatever, i don't
> care.

I'd rather it'd be a docstring parameter.

- Decorators are transformation tools. Which type hints are not.
- keywords should be few and used only for language features. Static 
analysis isn't and should never be a language feature. It's an 
extension, perhaps.
- Same with built-in functions... although a case could be made for a 
static analysis package, hmmm.

So I'd rather see:

     def myfunction(arg1, arg2):
     """
     Normal docstring.
     """ 
     "@typehint: (str, int) -> bool"
         return True 

This conforms to PEP 258, but not to PEP 8, but you can always use the 
triple quotes. I would just use the single-quote myself for matters of 
taste.

I removed the arguments names on purpose. They are only necessary on the 
PEP because type hinting is a part of the function header there. 
However, when using a documentation like pattern as above (or as in your 
own example), they can be safely removed, with the added benefit of 
making the syntax simpler.

Alternatively, because dangling strings are always considered 
documentation and completely ignored by the interpreter (PEP 258), one 
could also do:

     "@typehint: (str, int) -> bool"
     def myfunction(arg1, arg2):
     """
     Normal docstring.
     """ 
         return True 

Again the choice of triple quotes or not is something not worth 
debating.



More information about the Python-list mailing list