I want to access the country name using a phone number with Python. But for some input data it does not return anything, how can I fix this? In the Phonenumbers documentation, I spotted the following suspicious comment:
If the number has already been found valid for one region, then we don't know which region it belongs to so we return nothing.
import phonenumbers
from phonenumbers import geocoder
phone = '+39391359045341'
p = phonenumbers.parse(phone)
geocoder.country_name_for_number(p, 'en')
The reason your code fails is that
+39is used by multiple countries (Italy and the Vatican), and as the comment you quoted explains, in that case the function just returns nothing because the region is ambiguous. (A few functions inside of the library seem to just use the major region though).So here is my fixed function if you want the major region (returns
"Italy"):Or if you want all regions (returns
["Italy", "Vatican"])Original comment:
I was able to reproduce the issue of
country_name_for_numbernot returning anything. I checked the source code and it internally callsregion_code_for_country_codeto look up the 2 letter code (+39...->IT) and then uses aLOCALE_DATAdictionary inside of_region_display_nameto look up the code (IT->Italy). Interactively: