countryinfo Python Library

repository·main·Indexed 41 days ago

https://github.com/porimol/countryinfo

A lightweight Python module for retrieving geographic and demographic data about countries, including ISO 3166-1 codes, capitals, currencies, languages, and population. It features a comprehensive CountryInfo class, a CLI tool for terminal queries, and optional Pydantic v2 support for type-safe data validation.

Tokens
5.7K
Snippets
24
Records
26
Agent score
50%

What's inside countryinfo

  1. Install countryinfo via pip or Poetry

    main

    You can install countryinfo using pip or poetry. The library supports optional extras for fuzzy lookup and Pydantic models.

    Standard Installation

    pip install countryinfo

    Installation with Extras

    Use these commands to include additional functionality:

    • countryinfo[fuzzy]: Enables typo-tolerant country lookup.
    • countryinfo[pydantic]: Provides Pydantic v2 typed models.
    • countryinfo[all]: Installs all optional extras.
    pip install "countryinfo[fuzzy]"
    pip install "countryinfo[pydantic]"
    pip install "countryinfo[all]"

    Using Poetry

    poetry add countryinfo
    poetry add "countryinfo[fuzzy,pydantic]"
    pip install countryinfo
  2. Quick Start with CountryInfo

    main

    To use the library, import CountryInfo and initialize it with a country identifier. You can then call various methods to retrieve geographic and demographic data.

    from countryinfo import CountryInfo
    
    country = CountryInfo("Singapore")
    print(country.capital())      # Singapore
    print(country.iso(2))         # SG
    print(country.population())   # 5469700
    print(country.neighbors())    # [] — island, no land borders
    from countryinfo import CountryInfo
    
    country = CountryInfo("Singapore")
    print(country.capital())      # Singapore
    print(country.iso(2))         # SG
    print(country.population())   # 5469700
    print(country.neighbors())    # [] — island, no land borders
  3. Handle CountryNotFoundError and ValueError

    main

    When performing lookups, be prepared to handle the following errors:

    • CountryNotFoundError: Raised when a country name or code cannot be found. This is a subclass of LookupError.
    • ValueError: Raised if None or an empty string is passed to the CountryInfo constructor.
    from countryinfo import CountryInfo, CountryNotFoundError
    
    try:
        country = CountryInfo("Xanadu")
    except CountryNotFoundError as e:
        print(f"Error: {e}")
    
    try:
        CountryInfo(None)
    except ValueError:
        print("Invalid input")
  4. Retrieve all country data with .info()

    main

    The .info() method returns a dictionary containing all available metadata for the country, including ISO codes, area, borders, calling codes, capital, currencies, demonym, languages, coordinates, population, region, timezones, and links to Wikipedia/Google.

    from countryinfo import CountryInfo
    
    info = CountryInfo("Singapore").info()
    # Returns a dict containing 'name', 'ISO', 'area', 'borders', etc.
  5. Filter and query countries

    main

    Use these functions to perform bulk operations or searches across the entire dataset:

    • all_countries(): Returns a list of all CountryInfo objects.
    • filter_countries(**kwargs): Filters countries based on specific criteria. Supported keys are region, subregion, language, currency, border, calling_code, and tld. Multiple arguments are combined using AND logic.
    • CountryInfo.all(): A classmethod that returns the raw data for all countries as a dictionary {lowercase_name: {...}, ...}.
    from countryinfo import all_countries, filter_countries, CountryInfo
    
    # Get all capitals
    countries = all_countries()
    capitals = [c.capital() for c in countries]
    
    # Filter by region and currency
    eurozone = filter_countries(region="Europe", currency="EUR")
    
    # Get raw data
    raw_data = CountryInfo.all()
  6. Access specific country properties

    main

    Use the following methods on a CountryInfo instance to retrieve specific attributes:

    MethodDescription
    .name()English country name (proper casing)
    .iso(type)Returns ISO 3166-1 codes. Use .iso(2) for alpha-2, .iso(3) for alpha-3, or no arg for a dict containing all
    .alt_spellings()List of alternate spellings
    .area()Area in km²
    .borders()List of bordering countries as ISO alpha-3 codes
    .neighbors()List of bordering countries as CountryInfo objects
    .calling_codes()International calling codes
    .capital()Capital city name
    .capital_latlng()Latitude and longitude of the capital
    .currencies()List of currency codes
    .demonym()The demonym (e.g., 'Singaporean')
    .geo_json()GeoJSON FeatureCollection for country boundaries
    .languages()ISO 639-1 language codes
    .latlng()Approximate country center coordinates
    .native_name()Country name in its native tongue
    .population()Total population
    .provinces()List of provinces
    .region()Continent/Region
    .subregion()Specific subregion
    .timezones()Static UTC offset strings
    .timezone_names()IANA timezone names
    .current_utc_offset()DST-aware current UTC offset(s) (uses zoneinfo)
    .tld()Top-level domain
    .translations()Dictionary of names in major languages
    .wiki()Wikipedia URL
    .google()Google search URL
  7. Initialize CountryInfo with various identifiers

    main

    The CountryInfo constructor accepts several case-insensitive identifiers to resolve a country. Supported identifiers include:

    • English Name: CountryInfo("Singapore") or CountryInfo("singapore")
    • ISO alpha-2: CountryInfo("SG")
    • ISO alpha-3: CountryInfo("SGP")
    • ISO numeric: CountryInfo("702") (string) or CountryInfo(702) (int)
    • Native / Alternate Name: CountryInfo("Singapura")
    • Full Official Name: CountryInfo("Republic of Singapore")

    Error Handling

    • Raises ValueError if no identifier is supplied.
    • Raises CountryNotFoundError (which inherits from LookupError) if the identifier cannot be resolved to a known country.
    from countryinfo import CountryInfo
    
    # Examples of valid initialization
    country = CountryInfo("Singapore")
    country = CountryInfo("SG")
    country = CountryInfo(702)
  8. Use Pydantic models for type-safe data

    main

    If you install the [pydantic] extra (pip install "countryinfo[pydantic]"), you can convert a CountryInfo instance into a Pydantic model for structured access and validation.

    # Requires: pip install "countryinfo[pydantic]"
    from countryinfo import CountryInfo
    
    country = CountryInfo("Singapore")
    model = country.model()
    
    print(model.name)          # Singapore
    print(model.iso.alpha2)    # SG
    print(model.population)    # 5469700
  9. Get a Pydantic model from CountryInfo

    main

    You can convert a CountryInfo instance into a structured Pydantic model by calling the .model() method. This provides type-safe access to country attributes like capital and iso codes.

    from countryinfo import CountryInfo
    
    country = CountryInfo("Singapore")
    model = country.model()
    print(model.capital)   # Singapore
    print(model.iso.alpha2)  # SG
  10. Use the countryinfo CLI

    main

    The countryinfo command-line tool allows you to query country data directly from your terminal.

    Common Commands:

    • countryinfo <name/code>: Get full info for a country.
    • countryinfo <name/code> --field <name>: Get a specific field (e.g., capital, iso, current_utc_offset).
    • countryinfo --filter <key>=<value>: Filter countries (e.g., --filter region=Asia). Multiple filters can be combined.
    • countryinfo <name/code> --json: Output the result in JSON format.
    # Full info
    countryinfo Singapore
    
    # Specific field
    countryinfo SG --field iso
    
    # Filter and JSON output
    countryinfo --filter region=Europe currency=EUR --json
  11. Get all country information with .info()

    main

    The .info() method returns a comprehensive dictionary containing all available data for the country. This includes a generated google key for quick searching.

    The returned dictionary follows the CountryInfoDict schema, which includes fields like ISO, altSpellings, area, borders, capital, currencies, languages, latlng, population, region, timezones, and more.

    from countryinfo import CountryInfo
    
    country = CountryInfo("Singapore")
    data = country.info()
    print(data['name'])      # Singapore
    print(data['ISO'])      # {'alpha2': 'SG', 'alpha3': 'SGP', 'numeric': '702'}
    print(data['google'])   # https://www.google.com/search?q=Singapore