[Python-ideas] Type annotations in TypeError messages - Improved error reporting

Karthikeyan tir.karthi at gmail.com
Fri Jul 27 14:08:09 EDT 2018


Python 3 has support for type annotations. Normally when we call a function 
with too few arguments then it returns a TypeError message with required 
arguments name but it gives no information about the type of the variables 
when there are type annotations for the function. I have added a little 
patch to return type annotations for the parameters and return type when 
there are type errors. This doesn't affect the existing code but improves 
on the code that has type annotations. My C skills are low and there is a 
lot of room for improvement. Feedback welcome.

The code is available at 
https://github.com/tirkarthi/cpython/tree/error-message-annotations .  
Gist : https://gist.github.com/tirkarthi/8e6e01fde74398cac7a4eb7246169956

Sorry for the double post if you have received any since my previous post 
was rejected as I have not subscribed to the group.

A sample run is as below : 

# foo_signature.py

from typing import List, Dict
import sys

def get_profile_a(user_id: int, likes: Dict[str, int]) -> Dict[str, int]:
    return {'user_id': user_id, 'likes': len(likes)}

def get_profile_b(user_id, likes):
    return {'user_id': user_id, 'likes': len(likes.keys())}

if len(sys.argv) > 1:
    get_profile_a()
else:
    get_profile_b()

# Without type hinting

cpython git:(error-message-annotations) ./python foo_signature.py
Traceback (most recent call last):
  File "../backups/foo_signature.py", line 13, in <module>
    get_profile_b()
TypeError: get_profile_b() missing 2 required positional arguments: 
'user_id' and 'likes'

# With type hinting patch

cpython git:(error-message-annotations) ./python foo_signature.py 1
Traceback (most recent call last):
  File "../backups/foo_signature.py", line 11, in <module>
    get_profile_a()
TypeError: get_profile_a() missing 2 required positional arguments: 
'user_id' and 'likes'
annotation: (user_id: <class 'int'>, likes: typing.Dict[str, int], return: 
typing.Dict[str, int])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180727/0298feea/attachment-0001.html>


More information about the Python-ideas mailing list