API reference
The supported classes and exceptions are exported from pyworldatlas.
Database and normalization helpers are private implementation details.
Profile conventions
Public records are frozen dataclasses.
Optional scalar fields use
Nonewhen the captured source has no value.Repeated fields use tuples and are empty when no values are bundled.
The public model does not expose an entity-recognition or legal-status classification. The words country and area follow the documented source scope.
Country.sourcesidentifies sources used somewhere in the profile; it is not a field-by-field provenance map.
The public model focuses on stable geographic reference fields rather than current affairs, opinion, or speculative narrative. See Educational purpose and editorial policy for the source and editorial review required for a new field family.
Country identity provenance
English identity has three deliberately separate fields:
Country.nameis the familiar English display and lookup name.Country.official_nameis the canonical English UN M49 identity.Country.formal_nameis the sourced English long/formal identity for 240 profiles.Nonemeans the profile is outside the captured source scope.Country.has_distinct_formal_nametests whether the sourced formal form differs fromname.Atlas.countries_with_formal_namesreturns all covered profiles.
English formal names are indexed for lookup and carry a Factbook, UN Protocol,
or Wikidata source in Country.sources. The local-identity API is separate:
Country.local_namescontains one immutable sourced local identity.Country.local_name(language_code)returns the complete record orNone.name_inandofficial_name_inproject its short and formal forms.romanized_name_inandromanized_official_name_inreturn only romanization printed by the source.local_name_languageslists the covered language codes for one country.Atlas.countries_with_local_namesexposes complete local-name coverage and supports exact language, script, and evidence-kind filters.
Each LocalizedName carries kind and language_status plus its
SourceReference and exact source_locator. locale_display records
come from CLDR; national_official records are reviewed against UNGEGN. A
missing LocalizedName.formal_name means the national formal form is not in
the reviewed local layer. It says nothing about the English
Country.formal_name field. No translation or romanization is generated at runtime. See
Local names and writing systems for examples and evidence rules.
Reference-fact provenance
Country.anthem, motto, and demonym are optional convenience views
over the corresponding tuples. Anthem, motto, and demonym records carry their
own SourceReference and exact source locator. Currency, language, timezone,
and postal objects also expose their contributing source when present.
Anthems contain titles only. Mottos are a conservative reviewed source-listed layer and do not claim a particular legal status. See Country reference facts for coverage and interpretation rules.
Discovery calculations
Country.summary returns display-ready multiline text and deliberately
omits unavailable values. It is a presentation helper; use Country
attributes, to_dict, or discovery_card when a stable structured shape
matters.
Atlas.rank_countries returns CountryRanking rows for
documented sourced or directly derived metrics. Atlas.rank is its compact
alias. Atlas.nearest_capitals returns
CapitalDistance rows ordered by great-circle distance.
These methods describe bundled values and geographic relationships; they do not
score or judge countries.
Atlas.learning_topics lists the topics shared by flashcards and
quiz. Atlas.quiz adds deterministic distractors and answer positions
and returns QuizQuestion objects. These helpers do not
store learner answers, scores, or sessions.
Physical-geography provenance
Country.physical contains the source-reported coastline, elevation points,
mean elevation, source-listed rivers and lakes, and its climate profile.
Country.geography.area contains total, land, and water area plus the
directly calculated water percentage.
ClimateProfile.summary_source and classification_source keep the short
climate summary separate from the derived Köppen-Geiger classes. Class shares
come from the documented raster/polygon extraction and are not site-level
climate claims. River and Lake records preserve a source_label;
their length or area describes the whole source feature, including a shared
feature, rather than the portion within one country.
Distance input contract
Atlas.distance_between accepts Coordinate objects, two-item
(latitude, longitude) tuples, City objects, Capital objects, and
Country objects. String inputs are exact bundled city names. A Country
input uses its primary-capital coordinates.
Coordinate.format and Coordinate.dms provide display text without
changing the signed decimal-degree values. compass_direction_to converts
the initial bearing to a 4-, 8-, or 16-point compass label. It is an orientation
aid, not a route instruction.
City discovery
Atlas.city performs an exact city lookup and raises a clear exception for
missing or ambiguous names. Atlas.search_cities performs accent-tolerant
partial matching and returns an empty tuple when there are no matches.
Atlas.nearest_cities returns CityDistance rows
ordered by great-circle distance. Optional country arguments narrow either the
origin lookup or the returned places.
Border API provenance
The border API separates stored relationships from runtime calculations:
neighborsandshares_borderread accepted edges from the generated SQLite graph.shared_neighborsintersects two stored neighbor sets.border_pathperforms deterministic breadth-first search.border_crossingsreads the crossing count from that shortest path.has_land_routetests reachability in the graph.countries_reachable_by_landtraverses a connected component.BorderPathResult.namesandalpha2_codesare derived from its immutableCountryReferencevalues.
These methods do not use boundary geometry, maritime relationships, transport networks, or current border-access rules. The accepted-edge policy and source exceptions are documented in Land borders and paths and Data sources and freshness.
Profile field notes
Value |
Meaning |
|---|---|
|
Country population value from the captured GeoNames snapshot |
|
Population divided by sourced total area; |
|
Regional-indicator Unicode sequence derived from the alpha-2 code |
|
Sourced English long/formal identity; may equal |
|
Source currency identifier and CLDR English name; the whole value may be |
|
CLDR display symbol and standard fractional-digit count when available |
|
Source language code plus captured English name and likely script |
|
Timezone IDs observed on bundled capital and city records |
|
Captured country-level timezone records and seasonal/raw UTC offsets |
|
Source display format and optional validation expression |
|
First optional typed record from the corresponding source-aware tuple |
|
Source area components; |
|
Source-reported physical measurements |
|
Optional named |
|
Source-listed major features, not exhaustive inventories |
|
Plain-language summary plus represented Köppen-Geiger classes |
|
Signed WGS84 decimal degrees with constructor validation |
|
Captured place population value, not a live estimate |
Atlas
- class pyworldatlas.Atlas(database_path: str | Path | None = None)[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.
- 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
- class pyworldatlas.Country(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)[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.
- class pyworldatlas.CountryCodes(alpha2: str, alpha3: str | None, numeric: str | None, wikidata: str | None = None, geonames: int | None = None)[source]
Standard identifiers for a country or area.
- class pyworldatlas.LocalizedName(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)[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.
- class pyworldatlas.Currency(code: str, name: str | None = None, symbol: str | None = None, minor_unit_digits: int | None = None, source: SourceReference | None = None)[source]
A country’s currency as identified by the captured source snapshot.
- class pyworldatlas.Language(code: str, primary_code: str | None = None, name: str | None = None, script_code: str | None = None, source: SourceReference | None = None)[source]
A language associated with a country in the captured sources.
- class pyworldatlas.Timezone(id: str, january_utc_offset_hours: float, july_utc_offset_hours: float, raw_utc_offset_hours: float, source: SourceReference | None = None)[source]
A country timezone and its captured January, July, and raw offsets.
- class pyworldatlas.PostalCodeFormat(format: str, regex: str | None = None, source: SourceReference | None = None)[source]
A source-provided postal-code display format and validation expression.
- class pyworldatlas.NationalAnthem(title: str, english_title: str | None, source: SourceReference, source_locator: str)[source]
A national-anthem title without lyrics, audio, or contributor data.
- class pyworldatlas.NationalMotto(text: str, language_code: str, english_text: str | None, source: SourceReference, source_locator: str)[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.
- class pyworldatlas.Demonym(noun: str | None, adjective: str | None, language_code: str, source: SourceReference, source_locator: str)[source]
Source-preserved noun and adjective forms for a country or area.
- class pyworldatlas.CountryReference(name: str, alpha2: str, alpha3: str | None, numeric: str | None)[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.
- class pyworldatlas.CountryDiscoveryCard(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, ...] = ())[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.
Geographic models
- class pyworldatlas.Coordinate(latitude: float, longitude: float)[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.
- class pyworldatlas.Area(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)[source]
Country area measurements in square kilometres.
water_percentis derived fromwater_km2 / total_km2when both source values are available. Missing components remainNone.
- class pyworldatlas.ElevationPoint(name: str, elevation_m: float, is_approximate: bool = False, source_label: str | None = None)[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.
- class pyworldatlas.River(name: str, length_km: float | None, source_label: str)[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.
- class pyworldatlas.Lake(name: str, area_km2: float | None, water_type: str | None, source_label: str)[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.
- class pyworldatlas.ClimateZone(code: str, name: str, group: str, share_percent: float)[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.
- class pyworldatlas.ClimateProfile(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)[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.
- class pyworldatlas.PhysicalGeography(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)[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.
- class pyworldatlas.Geography(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))[source]
Core geographic classification and physical measurements.
- class pyworldatlas.Capital(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)[source]
A national capital sourced from GeoNames.
- class pyworldatlas.City(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)[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)".
Results and metadata
- class pyworldatlas.BorderPathResult(countries: tuple[CountryReference, ...], crossings: int)[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.
- class pyworldatlas.CountryRanking(position: int, country: CountryReference, metric: str, value: int | float, unit: str)[source]
One deterministic position in a country ranking.
- class pyworldatlas.CapitalDistance(country: CountryReference, capital: Capital, distance: float, unit: str)[source]
A capital ordered by great-circle distance from an origin.
- class pyworldatlas.CityDistance(country: CountryReference, city: City, distance: float, unit: str)[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().
- class pyworldatlas.CountryMatch(country: Country, matched_name: str, score: int)[source]
A ranked country-search result.
- class pyworldatlas.Flashcard(topic: str, prompt: str, answer: str, country: CountryReference)[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().
- class pyworldatlas.QuizQuestion(topic: str, prompt: str, choices: tuple[str, ...], answer: str, country: CountryReference)[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.
Exceptions
- exception pyworldatlas.DatasetNotFoundError[source]
Raised when the bundled SQLite database cannot be found.
- exception pyworldatlas.DatasetVersionError[source]
Raised when runtime and dataset schema versions disagree.
- exception pyworldatlas.DatasetIntegrityError[source]
Raised when the bundled dataset fails an integrity check.