Enhancement: add type annotations to API surface
See original GitHub issueI believe exceptions due to type errors when trying to parse the wrong datatype should be more clear.
I recently ran into a situation whereby I was inadvertently passing a PhoneNumber object type to the parse function. This resulted in the following error:
AttributeError: 'PhoneNumber' object has no attribute 'find'
Despite the fact I was passing a PhoneNumber object, it was not obvious to me in the moment that I needed to be passing a string based on the exception, which sent me investigating why that object lacked the attribute being called instead of letting me know that I was experiencing a TypeError and that the function was expecting a string in the first place.
This becomes more ambiguous if a user feeds the function an int, (which seems a much more likely mistake) which returns the following exception:
TypeError: object of type 'int' has no len()
The following code produces these exceptions depending on what is printed:
import phonenumbers
phone_number_int = 1111111111
phone_number_str = str(phone_number_int)
phone_number_object = phonenumbers.parse(phone_number_str, 'US')
phone_number_error = phonenumbers.parse(phone_number_int)
print(phone_number_error)
I believe a simple check of the number variable that raises a TypeError if not a string type and lets the user know the function is expecting a string would be helpful, and I would be happy to raise a pull request with this change.
Thank you.
Issue Analytics
- State:
- Created 2 years ago
- Comments:19 (16 by maintainers)
Top GitHub Comments
Thanks for the information; I think the distinction between “describe the API types” and “type-check the library itself” is very helpful.
In the near term, using
.pyi
files to address the former seems reasonable, particularly as it doesn’t have any impact on the main codebase.(In the longer term, I imagine I’ll eventually drop support for Python 2.x and then the annotations can be merged from the
.pyi
files intovar: Type
-style annotations in the main codebase.)Thanks also for the find in
PhoneMetadata.load_all
; I’ve got a fix in #205 (together with another more minor change that my experiments with type checking turned up). Were there any other findings that didn’t seem benign?Brilliant! Thanks for the reviews 😃
And if you move to Python versions that support inline annotations, the offer is very much open to move the stubs inline if wanted – hopefully that would be a quicker review!
A