API reference
Use this page to check an exact class, property, method, return type, or exception. If you are learning the package, begin with the Quickstart or a focused guide under Explore the atlas, then return here for details.
Find the right object
Start with |
Use it for |
Common results |
|---|---|---|
Opening the database and running lookups, searches, calculations, and learning helpers |
|
|
Reading one country or area profile |
Names, codes, capital, reference facts, physical geography, and sources |
|
Working with locations and physical features |
|
|
Inspecting structured calculations and learning material |
Rankings, distances, border paths, flashcards, quizzes, and metadata |
|
Handling missing, ambiguous, closed, or incompatible data |
Specific subclasses of |
|
Opening or exporting an installed 3D map edition |
|
How to read an entry
Each blue heading is a public Python signature. A property is read as an
attribute, such as country.flag. A method is called, such as
country.name_in("ja"). Text after the colon is the return type; | None
means the value may be unavailable in the bundled source layer.
Public records are frozen dataclasses. Repeated values are tuples, and a
missing collection is empty. Use to_dict() or the
corresponding model’s to_dict() method when you need JSON-compatible data.
Note
Atlas owns the read-only database connection. Use it
as a context manager. Models already returned by the atlas remain usable
after the context closes.
Atlas
The main entry point. Atlas handles country and city lookup, filtering,
distance calculations, border paths, rankings, learning helpers, dataset
metadata, and optional maps.
- class pyworldatlas.Atlas[source]
Open and explore the bundled, read-only world atlas.
With no arguments,
Atlasuses the SQLite dataset shipped inside the package. Passdatabase_pathonly when working with a compatible database built by the PyWorldAtlas pipeline. A context manager closes the database promptly; already materialized immutable models remain usable. Runtime lookups and calculations require no network access.- dataset_info() DatasetInfo[source]
Return the installed library, database schema, and dataset versions.
Record these values when a lesson or calculation must be reproducible.
- country(query: str) Country[source]
Return one country profile resolved from a name or standard code.
querymay be a familiar English name, indexed alias, alpha-2 code, alpha-3 code, or three-digit M49 code. Matching is case-insensitive and accent-tolerant. A missing or non-unique query raisesCountryNotFoundError, with suggestions when available.
- get(query: str, default: Country | None = None) Country | None[source]
Return a matching country, or
defaultinstead of raising.Use
country()when a missing profile should be treated as an error.defaultis returned for both missing and non-unique queries.
- map(country: str | Country, *, quality: str = 'auto') CountryMap[source]
Return an interactive offline 3D map for a country profile.
countryaccepts the same names and codes ascountry(), or an already loadedCountry.quality="auto"prefers Standard map data when installed and otherwise uses Overview data.The returned map opens in the default browser when its
show()method is called. Installpyworldatlas[maps]for Standard maps orpyworldatlas[maps-overview]for the smaller Overview edition.
- search_countries(query: str, *, limit: int = 20) tuple[CountryMatch, ...][source]
Return ranked partial-name matches for human-entered text.
Matching is case-insensitive and accent-tolerant. Exact matches rank before prefixes and substrings. The returned tuple is empty when no indexed name matches; use
country()for exact resolution.
- countries(*, continent: str | None = None, region: str | None = None, currency_code: str | None = None, language_code: str | None = None, script_code: str | None = None, timezone_id: str | None = None, coastal: bool | None = None, koppen_geiger_code: str | None = None, has_rivers: bool | None = None, has_lakes: bool | None = None) tuple[Country, ...][source]
Return countries alphabetically with optional exact profile filters.
Filters can be combined and use AND semantics. With no filters, every bundled profile is returned in display-name order.
Physical-data filters only include profiles covered by the relevant source layer. For example,
coastal=Falsemeans a sourced coastline of zero kilometres; it does not treat missing coastline data as zero.
- rank_countries(metric: str, *, limit: int | None = None, descending: bool = True, continent: str | None = None, region: str | None = None) tuple[CountryRanking, ...][source]
Rank countries by a documented sourced or directly derived metric.
Supported physical metrics include
"land_area","water_area","water_percent","coastline"`, ``"mean_elevation","highest_elevation","lowest_elevation"`, ``"river_count","lake_count", and"climate_zone_count". Existing population, total area, density, border, and city metrics remain available. Missing values are excluded.
- rank(metric: str, **kwargs: object) tuple[CountryRanking, ...][source]
Alias for
rank_countries()suited to exploratory sessions.
- climate_zone_codes() tuple[str, ...][source]
Return every represented Köppen-Geiger code in source legend order.
- countries_in_climate_zone(code: str) tuple[Country, ...][source]
Return profiles containing the exact Köppen-Geiger class
code.
- countries_with_river(name: str | None = None) tuple[Country, ...][source]
Return profiles with source-listed major rivers.
When
nameis supplied, it is matched case-insensitively against the concise feature name and retained source label. Results are alphabetical.
- countries_with_lake(name: str | None = None) tuple[Country, ...][source]
Return profiles with source-listed major lakes.
When
nameis supplied, it is matched case-insensitively against the concise feature name and retained source label. Results are alphabetical.
- countries_with_local_names(*, language_code: str | None = None, script_code: str | None = None, name_kind: str | None = None) tuple[Country, ...][source]
Return countries with sourced local-language name records.
Results are alphabetical.
language_codeandscript_codeare optional, case-insensitive exact filters such as"es","hi","Deva", or"Jpan". Every UN M49 record has one selected local identity. InspectLocalizedName.kindto distinguish reviewed national official forms from CLDR locale display names, or passname_kind="national_official"or"locale_display"directly.
- countries_with_formal_names() tuple[Country, ...][source]
Return countries and areas with a sourced English formal name.
Results are alphabetical. Some countries use the same sourced text for their short and formal forms; check
Country.has_distinct_formal_namewhen an application needs only distinct long forms.
- neighbors(country: str) tuple[Country, ...][source]
Return countries sharing a reviewed land border with
country.Results are alphabetized and immutable. Maritime neighbors, proximity, and mere point contacts are excluded. Countries and areas without an accepted land-border relationship return an empty tuple.
Return whether two countries share a reviewed land border.
Return alphabetized land neighbors shared by two countries.
- border_path(origin: str, destination: str) BorderPathResult | None[source]
Return a deterministic shortest land-border path, or
None.The path uses breadth-first search over the reviewed undirected graph. Both endpoints are included. Equal-length alternatives are resolved by alphabetic neighbor order.
Nonemeans the two entities have no path through accepted land-border relationships; it is not an error.
- border_crossings(origin: str, destination: str) int | None[source]
Return the fewest land-border crossings, or
Noneif unreachable.
- has_land_route(origin: str, destination: str) bool[source]
Return whether
originanddestinationare land-connected.This is derived at query time from the reviewed border graph; it does not use road, rail, ferry, maritime, or travel-access data. Identical endpoints return
Truebecause their shortest graph path has zero border crossings. Unknown country queries raiseCountryNotFoundError.
- countries_reachable_by_land(country: str) tuple[Country, ...][source]
Return every other entity in
country’s land-connected component.The starting country is excluded. Results are alphabetized; an island or otherwise borderless entity returns an empty tuple.
- countries_with_no_land_borders() tuple[Country, ...][source]
Return all bundled entities with no accepted land-border relation.
- sample_countries(*, count: int, continent: str | None = None, region: str | None = None, seed: int | str = 0) tuple[Country, ...][source]
Return a reproducible educational sample of country profiles.
Candidates are ranked with a versioned SHA-256 algorithm using their stable M49 identifiers. Results therefore do not depend on SQLite row order, global random state, or implementation details of
random.sample(). The same dataset, filters, count, and seed produce the same ordered result across supported Python versions.countmust be positive and cannot exceed the filtered population.continentandregionfollowcountries()semantics.
- learning_topics() tuple[str, ...][source]
Return topics supported by
flashcards()andquiz().The tuple is stable, alphabetized, and safe to use for menus, lesson builders, or playground controls.
- flashcards(*, topic: str, count: int, continent: str | None = None, region: str | None = None, seed: int | str = 0) tuple[Flashcard, ...][source]
Return deterministic, immutable geography flashcards.
Supported topics are
alpha_2_codes,alpha_3_codes,areas,border_counts,calling_codes,capitals,climate_zones,coastlines,continents,countries_from_capitals,currencies,flags,highest_points,language_codes,lakes,local_names,m49_codes,neighbors,rivers,population_density,populations,regions, andtop_level_domains. Countries missing the answer required by a topic are excluded before sampling. An impossible count raisesValueErrorrather than silently returning fewer cards.Population, area, and density answers describe the captured source snapshot. Neighbor and border-count answers are derived from the reviewed land-border graph. Local-name cards use the selected CLDR or UNGEGN identity record for every country and area. Flashcards are structured values, not an interactive game.
- quiz(*, topic: str, count: int, choices: int = 4, continent: str | None = None, region: str | None = None, seed: int | str = 0) tuple[QuizQuestion, ...][source]
Build deterministic multiple-choice questions from sourced facts.
topicaccepts every value returned bylearning_topics().choicesmust be an integer from 2 through 6. Questions, distractors, and answer positions remain stable for the same dataset, filters, and seed, making answer keys reproducible across supported Python versions.The method raises
ValueErrorwhen the filtered profiles do not provide enough distinct answers for the requested number of choices. No scoring, learner data, or session state is stored.
- major_cities(country: str, *, limit: int | None = None) tuple[City, ...][source]
Return populated places for a country, ordered by population and name.
limit=Nonereturns every bundled place for the country. The records come from the package snapshot and are not live population estimates.
- search_cities(query: str, *, country: str | None = None, limit: int = 20) tuple[City, ...][source]
Return ranked city-name matches from the bundled place table.
Matching is case-insensitive and accent-tolerant. Exact names rank first, followed by prefix and substring matches; population breaks ties. Pass
countryas a familiar country name or code to narrow the search. An empty result is returned when nothing matches.
- city(query: str, *, country: str | None = None) City[source]
Return one exact bundled city, optionally limited to a country.
Matching is case-insensitive and accent-tolerant. Pass a familiar country name or code when the city name is shared. Missing names raise
PlaceNotFoundError; ambiguous names raiseAmbiguousPlaceErrorwith example matches.
- coordinates(query: str, *, country: str | None = None) Coordinate[source]
Return WGS84 coordinates for an exact bundled city lookup.
This is shorthand for
atlas.city(query, country=country).coordinates.
- distance_between(first: str | Country | Capital | City | Coordinate | tuple[float, float], second: str | Country | Capital | City | Coordinate | tuple[float, float], *, unit: str = 'km', first_country: str | None = None, second_country: str | None = None) float[source]
Return great-circle distance between city, model, or coordinate inputs.
Accepted inputs are exact bundled-city names,
City,Capital,Country,Coordinate, or(latitude, longitude)tuples. Country objects use their primary capitals.unitaccepts"km","mi", or"nmi". The result is a surface measurement, not a road or flight route.
- nearest_capitals(origin: str | Country | Capital | City | Coordinate | tuple[float, float], *, limit: int = 5, unit: str = 'km', country: str | None = None, include_origin: bool = False) tuple[CapitalDistance, ...][source]
Return primary capitals nearest to a city, country, or coordinate.
String origins use the exact city lookup and may be constrained with
country. Pass aCountryto measure from its primary capital or aCoordinatefor an arbitrary starting point.unitaccepts"km","mi", or"nmi". Results are ordered nearest first with deterministic name tie-breaking.
- nearest_cities(origin: str | Country | Capital | City | Coordinate | tuple[float, float], *, limit: int = 5, unit: str = 'km', origin_country: str | None = None, within_country: str | None = None, include_origin: bool = False) tuple[CityDistance, ...][source]
Return bundled populated places nearest to an origin.
String origins are exact city names and can be disambiguated with
origin_country.within_countrylimits results to one country or area. By default, records at the origin’s exact coordinates are omitted. Distances are great-circle surface measurements, not road distances.
- close() None[source]
Close the read-only database connection.
Calling
close()more than once is safe. Queries on a closed atlas raiseAtlasClosedError; models returned earlier remain usable.
Country models
Country profile
Country is the complete immutable profile returned by
country(). Its convenience properties expose common
facts directly while preserving the typed records underneath them.
- class pyworldatlas.Country[source]
A sourced, immutable country profile from the offline atlas.
official_nameis the canonical English identity from UN M49.formal_nameis the sourced English long or formal form when the country or area is covered by the formal-name source layer.- property alpha2: str
Return the ISO alpha-2 code.
- property alpha3: str | None
Return the ISO alpha-3 code.
- property continent: str | None
Return the broad continent classification.
- property region: str | None
Return the UN region classification.
- property subregion: str | None
Return the UN subregion classification.
- property area_km2: float | None
Return sourced total area in square kilometres, when available.
- property land_area_km2: float | None
Return sourced land area in square kilometres, when available.
- property water_area_km2: float | None
Return sourced inland-water area in square kilometres, when available.
- property water_percent: float | None
Return the derived percentage of total area recorded as water.
- property physical: PhysicalGeography
Return structured physical-geography facts for this profile.
- property coastline_km: float | None
Return sourced coastline length in kilometres, when available.
- property mean_elevation_m: float | None
Return sourced mean elevation above sea level, when available.
- property highest_point: ElevationPoint | None
Return the sourced named highest point, when available.
- property lowest_point: ElevationPoint | None
Return the sourced named lowest point, when available.
- property rivers: tuple[River, ...]
Return source-listed major rivers; this is not an exhaustive inventory.
- property lakes: tuple[Lake, ...]
Return source-listed major lakes; this is not an exhaustive inventory.
- property climate: ClimateProfile
Return the climate summary and represented Köppen-Geiger classes.
- property is_coastal: bool | None
Return whether the source reports a positive coastline, or
None.
- property is_landlocked: bool | None
Return whether the source reports zero coastline, or
None.
- property flag_emoji: str | None
Return the regional-indicator flag derived from the alpha-2 code.
Emoji appearance depends on the operating system, font, and application.
Noneis returned if a profile ever lacks a valid two-letter code. The existingflagattribute is the same value.
- property has_distinct_formal_name: bool
Return whether the sourced English formal form differs from
name.Falsealso covers records outside the current formal-name source scope. Inspectformal_namedirectly when that distinction matters.
- property population_density: float | None
Return snapshot population per square kilometre when calculable.
This is a transparent ratio of
populationtoarea_km2, not a separately sourced official statistic.Nonerepresents a missing population, missing area, or non-positive area.
- property language_codes: tuple[str, ...]
Return the captured country language codes as an immutable tuple.
- property currency_code: str | None
Return the captured currency code, or
Nonewhen unavailable.
- property anthem: NationalAnthem | None
Return the first sourced anthem-title record, when available.
- property motto: NationalMotto | None
Return the first reviewed source-listed motto, when available.
- property timezone_ids: tuple[str, ...]
Return all captured country timezone identifiers.
- property major_city_count: int
Return the number of populated-place records bundled for this profile.
- property capital_coordinates: Coordinate | None
Return the primary capital’s coordinates, when a capital is available.
- property local_name_languages: tuple[str, ...]
Return language codes represented by sourced local identity records.
- local_name(language_code: str) LocalizedName | None[source]
Return the complete sourced local record for
language_code.Matching is case-insensitive.
Nonemeans that this dataset does not contain a selected record for that language; it does not mean the language or local name does not exist. No translation, English fallback, or romanization is invented.
- name_in(language_code: str) str | None[source]
Return the sourced short local name, without fallback.
- official_name_in(language_code: str) str | None[source]
Return the reviewed formal local name, without fallback.
This is populated only for
national_officiallocal records. It is separate from the Englishformal_nameprofile field.
- romanized_name_in(language_code: str) str | None[source]
Return a source-provided romanized short name, without generating one.
- romanized_official_name_in(language_code: str) str | None[source]
Return a source-provided romanized formal name, without generating one.
- reference() CountryReference[source]
Return a compact immutable reference suitable for results and prompts.
- discovery_card() CountryDiscoveryCard[source]
Return a compact educational view built entirely from this profile.
The card is safe to retain after the originating
Atlascloses and can be serialized withCountryDiscoveryCard.to_dict()orCountryDiscoveryCard.to_json().
- summary(*, local_language: str | None = None) str[source]
Return a readable, multiline introduction to this country profile.
The summary favors useful classroom facts and omits unavailable values. Pass a language code to request a particular bundled local name; with no code, the selected non-English local identity is used when present. This is a presentation helper rather than a serialization format—use
to_dict()when field names and machine-readable values matter.
- to_dict(include_history: bool = False) dict[str, Any][source]
Serialize this profile to JSON-compatible primitives.
include_historyis reserved for compatibility and currently has no effect because the bundled dataset has no historical series.
- to_json(indent: int | None = None, include_history: bool = False) str[source]
Serialize this profile as JSON.
include_historyis reserved for compatibility and currently has no effect because the bundled dataset has no historical series.
- __init__(name: str, official_name: str | None, names: tuple[LocalizedName, ...], aliases: tuple[str, ...], codes: CountryCodes, flag: str, geography: Geography, capitals: tuple[Capital, ...], major_cities: tuple[City, ...], sources: tuple[SourceReference, ...], local_names: tuple[LocalizedName, ...] = (), population: int | None = None, currency: Currency | None = None, languages: tuple[Language, ...] = (), calling_codes: tuple[str, ...] = (), top_level_domain: str | None = None, observed_timezones: tuple[str, ...] = (), formal_name: str | None = None, anthems: tuple[NationalAnthem, ...] = (), mottos: tuple[NationalMotto, ...] = (), demonyms: tuple[Demonym, ...] = (), timezones: tuple[Timezone, ...] = (), postal_code: PostalCodeFormat | None = None) None
Names, codes, and administrative metadata
These records describe identity, language, currency, timezone, and postal fields contained within a country profile.
- class pyworldatlas.CountryCodes[source]
Standard identifiers for a country or area.
- __init__(alpha2: str, alpha3: str | None, numeric: str | None, wikidata: str | None = None, geonames: int | None = None) None
- class pyworldatlas.LocalizedName[source]
A sourced country or area name in a selected local language.
kindis"national_official"for reviewed UNGEGN short/formal names and"locale_display"for Unicode CLDR territory display names.official_nameand the romanized fields remainNoneunless their source explicitly supplies those values.language_statusrecords why the language was selected, such as"official"or"de_facto_official".- property short_name: str
Return the short local-language form.
- property formal_name: str | None
Return the formal local-language form supplied by the source.
- property is_national_official: bool
Whether UNGEGN supplies a reviewed national official name.
- __init__(text: str, language_code: str | None, kind: str, preferred: bool, language_name: str | None = None, script_code: str | None = None, official_name: str | None = None, romanized_short_name: str | None = None, romanized_official_name: str | None = None, is_official_language: bool = False, source: SourceReference | None = None, source_locator: str | None = None, language_status: str | None = None) None
- class pyworldatlas.Currency[source]
A country’s currency as identified by the captured source snapshot.
- __init__(code: str, name: str | None = None, symbol: str | None = None, minor_unit_digits: int | None = None, source: SourceReference | None = None) None
- class pyworldatlas.Language[source]
A language associated with a country in the captured sources.
- __init__(code: str, primary_code: str | None = None, name: str | None = None, script_code: str | None = None, source: SourceReference | None = None) None
- class pyworldatlas.Timezone[source]
A country timezone and its captured January, July, and raw offsets.
- __init__(id: str, january_utc_offset_hours: float, july_utc_offset_hours: float, raw_utc_offset_hours: float, source: SourceReference | None = None) None
- class pyworldatlas.PostalCodeFormat[source]
A source-provided postal-code display format and validation expression.
- __init__(format: str, regex: str | None = None, source: SourceReference | None = None) None
Reference facts
Anthems contain titles only. Motto and demonym records are optional and retain their own source reference when available.
- class pyworldatlas.NationalAnthem[source]
A national-anthem title without lyrics, audio, or contributor data.
- __init__(title: str, english_title: str | None, source: SourceReference, source_locator: str) None
- class pyworldatlas.NationalMotto[source]
A reviewed source-listed national motto and selected language label.
The record does not infer a legal status.
english_textis the captured English label when the source supplies one; it may preserve the original phrase instead of translating it.- __init__(text: str, language_code: str, english_text: str | None, source: SourceReference, source_locator: str) None
- class pyworldatlas.Demonym[source]
Source-preserved noun and adjective forms for a country or area.
- __init__(noun: str | None, adjective: str | None, language_code: str, source: SourceReference, source_locator: str) None
Compact country views
These smaller records are returned by border paths and discovery helpers when a complete country profile would be unnecessary.
- class pyworldatlas.CountryReference[source]
A compact, immutable country identifier used in educational results.
The reference contains display and lookup identifiers only. It deliberately avoids nesting a complete
Countryprofile inside flashcards and discovery results.- __init__(name: str, alpha2: str, alpha3: str | None, numeric: str | None) None
- class pyworldatlas.CountryDiscoveryCard[source]
A compact, serializable teaching view of one materialized country.
Every value is copied from, or calculated directly from, an existing
Country. Creating a card never queries the database or network.- to_json(indent: int | None = None) str[source]
Serialize this discovery card as JSON without escaping Unicode text.
- __init__(country: CountryReference, flag_emoji: str | None, official_name: str | None, formal_name: str | None, capital: str | None, capital_coordinates: Coordinate | None, continent: str | None, region: str | None, subregion: str | None, population: int | None, area_km2: float | None, population_density: float | None, currency: Currency | None, language_codes: tuple[str, ...], calling_codes: tuple[str, ...], top_level_domain: str | None, observed_timezones: tuple[str, ...], local_names: tuple[LocalizedName, ...], major_city_count: int, source_ids: tuple[str, ...], anthem_title: str | None = None, motto_text: str | None = None, demonym: str | None = None, timezone_ids: tuple[str, ...] = (), coastline_km: float | None = None, highest_point: ElevationPoint | None = None, climate_zone_codes: tuple[str, ...] = ()) None
Geographic models
Coordinates and area
- class pyworldatlas.Coordinate[source]
A signed WGS84 coordinate in decimal degrees.
Use
format()for a compact classroom-friendly label,dms()for degrees/minutes/seconds, and the calculation methods for great-circle distance and direction. Latitude always comes before longitude.- property hemispheres: tuple[str, str]
Return the latitude and longitude hemispheres, such as
("N", "E").
- format(*, precision: int = 4) str[source]
Return signed coordinates as an easy-to-read hemisphere label.
Coordinate(35.6895, 139.6917).format()returns"35.6895° N, 139.6917° E".precisioncontrols decimal places and must be an integer from 0 through 8.
- dms(*, seconds_precision: int = 1) str[source]
Return degrees, minutes, and seconds with hemisphere letters.
seconds_precisioncontrols decimal places on the seconds value and must be an integer from 0 through 6.
- distance_to(other: Coordinate, *, unit: str = 'km') float[source]
Return great-circle distance using the WGS84 mean Earth radius.
unitaccepts kilometres ("km"), statute miles ("mi"), or nautical miles ("nmi"). This is a surface measurement, not a road or flight route.
- bearing_to(other: Coordinate) float[source]
Return the initial bearing to
otherin degrees from true north.The bearing is in the half-open range
[0, 360)and may change along a great-circle path. Coincident and antipodal points have no unique initial bearing and raiseValueError.
- compass_direction_to(other: Coordinate, *, points: int = 16) str[source]
Return a compass direction such as
"SE"for the initial bearing.pointsselects a 4-, 8-, or 16-point compass rose. The result describes the initial great-circle direction, which can change along a long route.
- midpoint_to(other: Coordinate) Coordinate[source]
Return the spherical midpoint on the great-circle path to
other.
- __init__(latitude: float, longitude: float) None
- class pyworldatlas.Area[source]
Country area measurements in square kilometres.
water_percentis derived fromwater_km2 / total_km2when both source values are available. Missing components remainNone.- __init__(total_km2: float | None = None, land_km2: float | None = None, water_km2: float | None = None, water_percent: float | None = None, disputed_km2: float | None = None) None
Physical geography
- class pyworldatlas.ElevationPoint[source]
A named highest or lowest point and its elevation above sea level.
A negative value is below sea level.
is_approximatepreserves an explicit approximation in the source; the numeric value is not made more precise by the package.source_labelretains the exact compact label from which the structured fields were parsed.- __init__(name: str, elevation_m: float, is_approximate: bool = False, source_label: str | None = None) None
- class pyworldatlas.River[source]
A source-listed major river associated with a country profile.
length_kmis the full river length reported by the source, including for rivers shared across countries. It is not the length inside this one profile.source_labelpreserves shared/source/mouth context.- __init__(name: str, length_km: float | None, source_label: str) None
- class pyworldatlas.Lake[source]
A source-listed major lake associated with a country profile.
area_km2is the full lake area reported by the source, including for a shared lake.water_typeis"freshwater"or"saltwater"when the source supplies that classification.- __init__(name: str, area_km2: float | None, water_type: str | None, source_label: str) None
- class pyworldatlas.ClimateZone[source]
A Köppen-Geiger class detected within a country or area profile.
share_percentis a latitude-area-weighted share derived from the source’s 0.1-degree 1991-2020 raster and pinned map-unit polygons. Classes below the documented extraction threshold are omitted.- __init__(code: str, name: str, group: str, share_percent: float) None
- class pyworldatlas.ClimateProfile[source]
A plain-language climate summary and reviewed Köppen-Geiger classes.
- property dominant_zone: ClimateZone | None
Return the largest represented Köppen-Geiger class, if available.
- property zone_codes: tuple[str, ...]
Return represented Köppen-Geiger codes in descending area share.
- __init__(summary: str | None = None, koppen_geiger_zones: tuple[ClimateZone, ...] = (), reference_period: str | None = None, resolution_degrees: float | None = None, minimum_share_percent: float | None = None, summary_source: SourceReference | None = None, classification_source: SourceReference | None = None) None
- class pyworldatlas.PhysicalGeography[source]
Structured physical facts extracted for a country or area profile.
Rivers and lakes are source-listed major features, not exhaustive inventories. A missing tuple means that the source did not list a feature; it does not assert that the feature does not exist.
- property is_coastal: bool | None
Return whether the sourced coastline is positive, or
None.
- property is_landlocked: bool | None
Return whether the source reports zero coastline, or
None.
- __init__(coastline_km: float | None = None, mean_elevation_m: float | None = None, highest_point: ElevationPoint | None = None, lowest_point: ElevationPoint | None = None, rivers: tuple[River, ...] = (), lakes: tuple[Lake, ...] = (), climate: ClimateProfile = ClimateProfile(summary=None, koppen_geiger_zones=(), reference_period=None, resolution_degrees=None, minimum_share_percent=None, summary_source=None, classification_source=None), source: SourceReference | None = None, source_locator: str | None = None) None
- class pyworldatlas.Geography[source]
Core geographic classification and physical measurements.
- __init__(continent: str | None, region: str | None, subregion: str | None, area: Area = Area(total_km2=None, land_km2=None, water_km2=None, water_percent=None, disputed_km2=None), centroid: Coordinate | None = None, landlocked: bool | None = None, physical: PhysicalGeography = PhysicalGeography(coastline_km=None, mean_elevation_m=None, highest_point=None, lowest_point=None, rivers=(), lakes=(), climate=ClimateProfile(summary=None, koppen_geiger_zones=(), reference_period=None, resolution_degrees=None, minimum_share_percent=None, summary_source=None, classification_source=None), source=None, source_locator=None)) None
Places
Capital and City include validated coordinates and captured population
values. Place populations are snapshot values, not live estimates.
- class pyworldatlas.Capital[source]
A national capital sourced from GeoNames.
- __init__(name: str, country_code: str, coordinates: Coordinate, role: str = 'official', primary: bool = True, largest_city: bool | None = None, population: int | None = None, elevation_m: float | None = None, timezone_id: str | None = None, alternate_names: tuple[str, ...] = (), geonames_id: int | None = None) None
- class pyworldatlas.City[source]
An immutable bundled populated place.
Every city has a display name, country code, and WGS84 coordinates. Population, elevation, timezone, capital roles, alternate names, and the GeoNames identifier are optional snapshot fields.
- property label: str
Return a compact place label such as
"Tokyo (JP)".
- __init__(name: str, country_code: str, coordinates: Coordinate, population: int | None = None, elevation_m: float | None = None, timezone_id: str | None = None, capital_roles: tuple[str, ...] = (), alternate_names: tuple[str, ...] = (), geonames_id: int | None = None) None
Results and metadata
Calculations and learning helpers return typed records rather than loosely
structured dictionaries. Their to_dict() methods provide portable output.
- class pyworldatlas.BorderPathResult[source]
A shortest path through the reviewed land-border graph.
countriesincludes both endpoints in travel order.crossingsis therefore one fewer than the number of country references. The value is detached from the database and remains usable after itsAtlascloses.- property origin: CountryReference
Return the first country in the path.
- property destination: CountryReference
Return the last country in the path.
- property names: tuple[str, ...]
Return country display names in path order.
- property alpha2_codes: tuple[str, ...]
Return alpha-2 country codes in path order.
- to_json(indent: int | None = None) str[source]
Serialize this path as JSON without escaping Unicode text.
- __init__(countries: tuple[CountryReference, ...], crossings: int) None
- class pyworldatlas.CountryRanking[source]
One deterministic position in a country ranking.
- __init__(position: int, country: CountryReference, metric: str, value: int | float, unit: str) None
- class pyworldatlas.CapitalDistance[source]
A capital ordered by great-circle distance from an origin.
- __init__(country: CountryReference, capital: Capital, distance: float, unit: str) None
- class pyworldatlas.CityDistance[source]
A nearby populated place and its great-circle distance from an origin.
The compact country reference disambiguates city names.
unitrecords the unit requested frompyworldatlas.Atlas.nearest_cities().- to_json(indent: int | None = None) str[source]
Serialize this nearby-city result without escaping Unicode text.
- __init__(country: CountryReference, city: City, distance: float, unit: str) None
- class pyworldatlas.Flashcard[source]
A deterministic geography study prompt and answer.
Flashcards contain no scoring, session state, or hidden random state. The
topicvalue identifies the documented generator used bypyworldatlas.Atlas.flashcards().- to_json(indent: int | None = None) str[source]
Serialize this flashcard as JSON without escaping Unicode text.
- __init__(topic: str, prompt: str, answer: str, country: CountryReference) None
- class pyworldatlas.QuizQuestion[source]
A deterministic multiple-choice geography question.
Choices are stored in display order and
answeris always one of them. Useanswer_numberfor a one-based classroom answer key oris_correct()to check either a displayed answer or choice number.- property answer_number: int
Return the correct choice number using one-based classroom numbering.
- is_correct(choice: str | int) bool[source]
Check an answer string or a one-based choice number.
Text matching ignores surrounding whitespace and letter case. Invalid choice numbers return
False; unsupported input types raiseTypeError.
- to_json(indent: int | None = None) str[source]
Serialize this question without escaping Unicode text.
- __init__(topic: str, prompt: str, choices: tuple[str, ...], answer: str, country: CountryReference) None
Exceptions
Catch a specific exception when the distinction matters, or catch
AtlasError for package-level lookup, dataset, and lifecycle failures.
- exception pyworldatlas.AtlasError[source]
Base class for atlas errors.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.AtlasClosedError[source]
Raised when a closed atlas is used.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.DatasetError[source]
Base class for bundled-dataset errors.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.DatasetNotFoundError[source]
Raised when the bundled SQLite database cannot be found.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.DatasetVersionError[source]
Raised when runtime and dataset schema versions disagree.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.DatasetIntegrityError[source]
Raised when the bundled dataset fails an integrity check.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.CountryNotFoundError[source]
Raised when a country query has no match.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.AmbiguousCountryError[source]
Raised when a country query has multiple equally valid matches.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.PlaceNotFoundError[source]
Raised when a place query has no match.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.AmbiguousPlaceError[source]
Raised when a place query is ambiguous.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
Optional maps
These objects are installed by pyworldatlas[maps] or
pyworldatlas[maps-overview]. See Interactive 3D maps before depending on the
experimental map API.
- class pyworldatlas_mapview.CountryMap[source]
A lazily loaded interactive 3D country map.
Use
show()to open a standalone offline browser view. Usefigure()when direct Plotly customization or notebook display is preferred.- classmethod from_country(country: object, *, quality: str = 'auto') CountryMap[source]
Create a map request from a PyWorldAtlas country profile.
- property quality: str
Return the installed map quality this request will use.
- property resolution_arc_minutes: int
Return the nominal elevation sampling interval in arc-minutes.
- figure() object[source]
Return a ready-to-display
plotly.graph_objects.Figure.The figure contains elevation and climate surface controls, terrain height choices, optional river and capital labels, a country outline, source-provided river centerlines, and the primary capital when coordinates are available.
- to_html(*, auto_rotate: bool = False, rotation_speed: float = 1.0) str[source]
Return a complete standalone HTML document with Plotly embedded.
The document includes rotation, speed, and high-resolution PNG export controls. Set
auto_rotate=Trueto begin rotating when the page opens.rotation_speedaccepts values from0.25through3;1completes a turn in about twenty seconds.
- write_html(path: str | Path, *, auto_rotate: bool = False, rotation_speed: float = 1.0) Path[source]
Write a standalone offline HTML map and return its resolved path.
auto_rotateandrotation_speedselect the document’s initial motion state. The reader can still pause or adjust rotation in the exported viewer.
- show(*, auto_rotate: bool = False, rotation_speed: float = 1.0) Path[source]
Open the interactive map in the default browser and return its path.
Set
auto_rotate=Trueto start the map in motion. The generated browser controls can pause rotation, change its speed, and download a high-resolution PNG of the current view.
- __init__(alpha2: str, country_name: str, flag: str | None = None, capital_name: str | None = None, capital_latitude: float | None = None, capital_longitude: float | None = None, requested_quality: str = 'auto') None
Data contracts and provenance
Country identity
Country.name is the familiar English display and lookup name.
Country.official_name is the canonical English UN M49 identity, while
Country.formal_name is the sourced English long or formal identity when
that source layer covers the profile.
Country.local_names contains the selected sourced local identity.
name_in(), official_name_in(), and the romanization helpers project
values from that record; they do not translate or romanize text at runtime.
Each LocalizedName retains its language, script, evidence kind, source, and
source locator. See Local names and writing systems for the complete evidence rules.
Reference and discovery facts
Anthem, motto, demonym, currency, language, timezone, and postal records expose
their contributing source when one is bundled. Country.sources lists
sources used somewhere in the profile; it is not a field-by-field provenance
map. See Country reference facts for coverage and interpretation rules.
Country.summary() is presentation-ready text that omits unavailable facts.
Use model attributes, to_dict(), or discovery_card() when a stable
structured shape matters. Rankings describe sourced or directly calculated
values; they do not score or judge countries. Quiz and flashcard helpers are
deterministic and do not store learner answers or sessions.
Physical geography
Country.physical contains coastline, elevation points, mean elevation,
source-listed rivers and lakes, and climate. Country.geography.area contains
total, land, and water area plus the directly calculated water percentage.
Köppen-Geiger shares describe the portion represented by the documented raster and polygon extraction. They are not site-level climate claims. River lengths and lake areas describe the complete source feature, including shared features, rather than only the portion within one profile. See Physical geography and Data quality and limitations for limits.
Coordinates, cities, and distance
Atlas.distance_between() accepts coordinates, two-item latitude/longitude
tuples, cities, capitals, countries, and exact bundled city names. A country
uses its primary-capital coordinates. Distances are great-circle surface
measurements; compass labels are orientation aids, not route instructions.
Atlas.city() performs exact lookup and reports ambiguous names.
search_cities() performs accent-tolerant partial matching, while
nearest_cities() orders results by great-circle distance. Optional country
arguments narrow the lookup or returned places.
Land borders
Neighbor and path methods use the reviewed, undirected border graph. Shortest paths are deterministic breadth-first searches over stored relationships. They do not use boundary geometry, maritime relationships, transport networks, or current crossing rules. See Land borders and paths for the accepted-edge policy and interpretation limits.
Publication scope
The public model focuses on stable geographic reference data rather than
current affairs, opinion, or speculative narrative. Missing scalar values are
None and are never invented to fill a source gap. See
Educational purpose and editorial policy and Data sources and freshness for the publication and
source policies.