The reason your code fails is that +39
is 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"
):
import phonenumbers.geocoder
def country_name_for_number(p: phonenumbers.PhoneNumber, lang="en") -> str:
rc = phonenumbers.geocoder.region_code_for_country_code(p.country_code)
return phonenumbers.geocoder._region_display_name(rc, lang)
Or if you want all regions (returns ["Italy", "Vatican"]
)
def country_names_for_number(p: phonenumbers.PhoneNumber, lang="en") -> list[str]:
rcs = phonenumbers.geocoder.region_codes_for_country_code(p.country_code)
return [phonenumbers.geocoder._region_display_name(rc, lang) for rc in rcs]
Original comment:
I was able to reproduce the issue of country_name_for_number
not returning anything. I checked the source code and it internally calls region_code_for_country_code
to look up the 2 letter code (+39...
-> IT
) and then uses a LOCALE_DATA
dictionary inside of _region_display_name
to look up the code (IT
-> Italy
). Interactively:
import phonenumbers.geocoder
c = phonenumbers.parse("+39391359045341")
print(phonenumbers.geocoder.country_name_for_number(c, "en")) # returns 'None'?!
print(phonenumbers.geocoder.region_code_for_country_code(c.country_code)) # 'IT'
print(phonenumbers.geocoder._region_display_name("IT", "en")) # Italy