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.
The small installed pyworldatlas command is documented in the
Quickstart. This page covers the complete Python API.
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, places, and physical features |
|
|
Inspecting structured calculations, statistics, and learning material |
Rankings, distances, border paths, sun times, antipodes, statistic series, flashcards, quizzes, and metadata |
|
Handling missing, ambiguous, closed, or incompatible data |
Specific subclasses of |
|
Opening or exporting a 3D country map or a world map of a statistic |
|
|
Installing and listing optional packs from Python |
|
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, city, and place lookup;
nearby-place search; filtering; distances, sun times, and antipodes; border
paths and rankings; flashcards and quizzes; dataset metadata; and the optional
maps, landmarks, and statistics packs.
The examples on this page assume an open atlas, made with
from pyworldatlas import Atlas and atlas = Atlas(). Every example is run
as a test, so what you see is what you get.
- 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.data_dirselects the folder of optional data packs, such as 3D maps. It defaults toPYWORLDATLAS_DATAor a per-user folder; seepyworldatlas.packs.- PLACE_QUIZ_TOPICS = ('closer_to_equator', 'higher', 'kinds')
Topics about famous places that
quiz()accepts besideslearning_topics().
- __init__(database_path: str | Path | None = None, *, data_dir: str | Path | None = None) None[source]
- classmethod __new__(*args, **kwargs)
Look things up
Find one country, city, or place by name or code.
- Atlas.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. Missing queries raiseCountryNotFoundError, with suggestions when available. A name shared by multiple profiles raisesAmbiguousCountryErrorand lists the matches.- Parameters:
query – A country name (
"Japan"), alias, alpha-2 code ("JP"), alpha-3 code ("JPN"), or M49 code ("392").- Returns:
The full
Countryprofile.- Raises:
CountryNotFoundError – Nothing matches. The message suggests close spellings, such as “Did you mean Japan?”.
AmbiguousCountryError – The name fits more than one country.
Example
>>> atlas.country("Japan") Country(name='Japan', alpha2='JP') >>> atlas.country("DE").name 'Germany' >>> atlas.country("392").name 'Japan'
- Atlas.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.- Parameters:
query – A country name or code, as for
country().default – What to return when nothing matches.
- Returns:
The
Country, ordefault.
Example
>>> atlas.get("FR") Country(name='France', alpha2='FR') >>> atlas.get("Atlantis") is None True
- Atlas.find(query: str, *, limit: int = 10) tuple[Country | Place, ...][source]
Find anything by name: countries, cities, regions, and landmarks.
One search for human-entered text. A country that the query names exactly (by name, alias, or code) comes first as a full
Countryprofile; then come the best-known places fromsearch_places(), where a country-level place is replaced by itsCountryprofile.atlas.find("Luxembourg")gives the country and then its capital city.- Parameters:
query – Any name, such as
"Luxembourg"or"Kilimanjaro".limit – The most results to return.
- Returns:
Example
>>> atlas.find("Luxembourg", limit=2) (Country(name='Luxembourg', alpha2='LU'), Place(english_name='Luxembourg', kind='capital city', country_code='LU'))
- Atlas.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.- Parameters:
query – Part of a country name, such as
"guin".limit – The most matches to return.
- Returns:
CountryMatchrows, best match first.
Example
>>> atlas.search_countries("guin", limit=3) (CountryMatch('Guinea'), CountryMatch('Guinea-Bissau'), CountryMatch('Equatorial Guinea'))
- Atlas.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.- Parameters:
query – The city’s name, in any case and with or without accents.
country – The country, when several cities share the name.
- Returns:
The
City.- Raises:
PlaceNotFoundError – No city has this name. The message suggests close spellings.
AmbiguousPlaceError – Several cities share the name; pass
country.
Example
>>> atlas.city("Lima") City(name='Lima', country_code='PE') >>> atlas.city("bogota").name 'Bogotá'
- Atlas.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.- Parameters:
query – Part of a city name.
country – Search only in this country.
limit – The most cities to return.
- Returns:
Cityrecords, best match first.
Example
>>> atlas.search_cities("sao paulo", limit=2) (City(name='São Paulo', country_code='BR'),)
- Atlas.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.- Parameters:
country – A country name or code.
limit – The most cities to return, or
Nonefor all.
- Returns:
Cityrecords, largest first.
Example
>>> atlas.major_cities("Japan", limit=3) (City(name='Tokyo', country_code='JP'), City(name='Yokohama', country_code='JP'), City(name='Osaka', country_code='JP'))
- Atlas.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.- Parameters:
query – The city’s name.
country – The country, when several cities share the name.
- Returns:
The city’s
Coordinate.
Example
>>> print(atlas.coordinates("Nairobi")) Coordinate(latitude=-1.28333, longitude=36.81667)
- Atlas.place(query: str, *, kind: str | None = None, country: str | None = None) Place[source]
Return the best-known place with exactly this name.
atlas.place("Kilimanjaro")is the mountain andatlas.place("Lake Victoria")the African lake. Narrow withkindorcountryto pick a less famous namesake. RaisesPlaceNotFoundErrorwhen no place has this exact name.- Parameters:
query – The place’s exact name.
kind – Pick a place of this kind, such as
"mountain".country – Pick a place in this country.
- Returns:
The
Place.- Raises:
PlaceNotFoundError – No place has this name. The message suggests close spellings.
Example
>>> atlas.place("Kilimanjaro") Place(english_name='Mount Kilimanjaro', kind='mountain', country_code='TZ') >>> atlas.place("Kilimanjaro").elevation_m 5895
- Atlas.search_places(query: str, *, kind: str | None = None, category: str | None = None, country: str | None = None, limit: int = 10) tuple[Place, ...][source]
Find places on Earth by name, best known first.
Searches the bundled school atlas (about 200,000 places: every country, region, town of 5,000 people or more, and well-known mountain, lake, river, island, and landmark) plus any installed place packs. Local and English names both match, without regard to case or accents:
"Lake Titicaca"finds"Lago Titicaca". Exact names come first, then names that start with the query; better-known places break ties.Narrow results with
kind(seeplace_kinds()),category(seeplace_categories()), orcountry.- Parameters:
query – A name or the start of one.
kind – Keep only this kind, such as
"lake".category – Keep only this category, such as
"water".country – Keep only places in this country.
limit – The most places to return.
- Returns:
Placerecords, best match first.
Example
>>> atlas.search_places("Titicaca", limit=1) (Place(english_name='Lake Titicaca', kind='lake', country_code='BO'),)
- Atlas.places_in(country: str | Country, *, kind: str | None = None, category: str | None = None, limit: int = 20) tuple[Place, ...][source]
Return the best-known places in a country from the school atlas.
Towns, mountains, lakes, landmarks, and more, best known first. Narrow with
kind(seeplace_kinds()) orcategory(seeplace_categories()). The capital, whole regions, schools, airports, and river points are left out unless asked for bykind.- Parameters:
country – A country name, code, or profile.
kind – Keep only this kind, such as
"lake".category – Keep only this category, such as
"water".limit – The most places to return.
- Returns:
Placerecords, best known first.
Example
>>> atlas.places_in("Peru", kind="lake", limit=2) (Place(english_name='Lake Junín', kind='lake', country_code='PE'),)
- static Atlas.place_kinds() tuple[str, ...][source]
Return every place kind accepted by place searches, such as
"volcano".- Returns:
Kind names for the
kindargument of place searches.
Example
>>> "volcano" in atlas.place_kinds() True
- static Atlas.place_categories() tuple[str, ...][source]
Return the general place categories, such as
"water"and"landform".- Returns:
Category names for the
categoryargument of place searches.
Example
>>> atlas.place_categories() ('area', 'forest', 'landform', 'landmark', 'region', 'route', 'town', 'undersea', 'water')
Filter and rank
Pick countries that match, and put them in order.
- Atlas.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, river: str | None = None, lake: str | None = None, climate_zone: str | None = None, land_borders: bool | None = None) tuple[Country, ...][source]
Return countries alphabetically, keeping only those that match every filter.
This is the one place to filter countries. 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.- Parameters:
continent – Keep countries on this continent, such as
"Africa".region – Keep countries in this UN region or subregion.
currency_code – Keep countries using this currency, such as
"EUR".language_code – Keep countries with this language, such as
"es".script_code – Keep countries writing in this script, such as
"Cyrl".timezone_id – Keep countries in this time zone, such as
"Asia/Tokyo".coastal –
Truefor a coastline,Falsefor landlocked.koppen_geiger_code – Older name for
climate_zone.has_rivers – Keep countries with (or without) listed major rivers.
has_lakes – Keep countries with (or without) listed major lakes.
river – Keep countries a river flows through; part of the name is enough, in any case.
lake – Keep countries with this lake; part of the name is enough.
climate_zone – Keep countries with this Köppen-Geiger zone, a code from
climate_zone_codes()such as"Cfb".land_borders –
Falsefor islands and other countries with no land border,Truefor the rest.
- Returns:
Matching
Countryprofiles, alphabetical.- Raises:
ValueError – The climate zone is unknown.
Example
>>> len(atlas.countries(continent="Africa", coastal=False)) # landlocked 16 >>> atlas.countries(river="Danube")[:3] (Country(name='Austria', alpha2='AT'), Country(name='Bulgaria', alpha2='BG'), Country(name='Croatia', alpha2='HR')) >>> len(atlas.countries(land_borders=False)) 85
- Atlas.rank(metric: str, *, year: int | None = None, limit: int | None = None, descending: bool = True, continent: str | None = None, region: str | None = None) tuple[CountryRanking, ...][source]
Rank countries by anything the atlas can measure, largest first.
- Parameters:
metric – A profile metric such as
"area","coastline", or"border_count"(all are listed inrank_countries()), or a statistic such as"life_expectancy"fromindicators().year – Rank a statistic for one year. Without it, each country uses its latest published value, and the row’s
yearsays which year that is.limit – Keep only the first
limitrows.descending –
Falseranks smallest first.continent – Rank only countries on this continent.
region – Rank only countries in this region or subregion.
- Returns:
CountryRankingrows that print as#1 Canada: 202,080 km. Every row names itssource. Missing values are left out, never guessed.- Raises:
ValueError – The metric is unknown. The message suggests a close spelling and lists the choices.
"population"ranks the bundled GeoNames snapshot; with ayearit ranks the World Bank figures from the statistics pack. Ranking orders numbers only; it says nothing about which is better.Example
>>> print(atlas.rank("coastline", limit=1)[0]) #1 Canada: 202,080 km >>> atlas.rank("coastline", continent="Oceania", limit=2) (CountryRanking('#1 Australia: 25,760 km'), CountryRanking('#2 New Zealand: 15,134 km')) >>> atlas.rank("life_expectancy", year=2020, limit=1) (CountryRanking('#1 Monaco: 86.1 years (2020)'),)
- Atlas.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.- Parameters:
count – How many countries to pick.
continent – Pick only from this continent.
region – Pick only from this region or subregion.
seed – The same seed always picks the same countries.
- Returns:
The picked
Countryprofiles.- Raises:
ValueError –
countis not positive or is larger than the choices.
Example
>>> atlas.sample_countries(count=3, continent="Europe", seed="class-1") (Country(name='Andorra', alpha2='AD'), Country(name='Hungary', alpha2='HU'), Country(name='Monaco', alpha2='MC'))
- Atlas.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.- Parameters:
language_code – Keep names in this language, such as
"hi".script_code – Keep names in this script, such as
"Deva".name_kind –
"national_official"or"locale_display".
- Returns:
Matching
Countryprofiles, alphabetical.
Example
>>> atlas.countries_with_local_names(language_code="pt")[:2] (Country(name='Angola', alpha2='AO'), Country(name='Brazil', alpha2='BR'))
- Atlas.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.- Returns:
Matching
Countryprofiles, alphabetical.
Example
>>> france = atlas["France"] >>> france in atlas.countries_with_formal_names() True >>> france.formal_name 'French Republic'
- Atlas.climate_zone_codes() tuple[str, ...][source]
Return every represented Köppen-Geiger code in source legend order.
- Returns:
Codes such as
"Af"(tropical rainforest) for use withcountries(climate_zone=...).
Example
>>> atlas.climate_zone_codes()[:5] ('Af', 'Am', 'Aw', 'BWh', 'BWk')
- Atlas.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. Each row names itssource.rank()does the same and also ranks statistics; prefer it in new code.- Parameters:
metric – One of the metrics above, or
"population","area","population_density","border_count", or"major_city_count".limit – Keep only the first
limitrows.descending –
Falseranks smallest first.continent – Rank only countries on this continent.
region – Rank only countries in this region or subregion.
- Returns:
CountryRankingrows, first place first.- Raises:
ValueError – The metric is unknown.
Example
>>> atlas.rank_countries("coastline", limit=2) (CountryRanking('#1 Canada: 202,080 km'), CountryRanking('#2 Indonesia: 54,716 km'))
Measure
Distances, the nearest things, the sun, and the other side of the Earth.
- Atlas.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.- Parameters:
first – Where to measure from.
second – Where to measure to.
unit –
"km","mi", or"nmi".first_country – The country of
first, when its name is shared.second_country – The country of
second, when its name is shared.
- Returns:
a number that prints with its unit.
- Return type:
A
Distance
Example
>>> atlas.distance_between("Paris", "Tokyo") Distance(9712.5, 'km') >>> print(atlas.distance_between("Paris", "Tokyo", unit="mi")) 6,035 mi
- Atlas.capitals_near(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.- Parameters:
origin – A city or place name, a country (its capital), any model with coordinates, or a
(latitude, longitude)tuple.limit – The most capitals to return.
unit –
"km","mi", or"nmi".country – The country of
origin, when its name is shared.include_origin – Also list a capital at the origin itself.
- Returns:
CapitalDistancerows, nearest first.
Example
>>> atlas.capitals_near("Paris", limit=2) (CapitalDistance('Brussels, Belgium · 264 km'), CapitalDistance('Luxembourg, Luxembourg · 287 km'))
- Atlas.cities_near(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.- Parameters:
origin – A city or place name, a country (its capital), any model with coordinates, or a
(latitude, longitude)tuple.limit – The most cities to return.
unit –
"km","mi", or"nmi".origin_country – The country of
origin, when its name is shared.within_country – Return only cities in this country.
include_origin – Also list a city at the origin itself.
- Returns:
CityDistancerows, nearest first.
Example
>>> atlas.cities_near("Reykjavik", limit=2) (CityDistance('Tórshavn (FO) · 795 km'), CityDistance('Aberdeen (GB) · 1,321 km'))
- Atlas.places_near(origin: str | Country | Capital | City | Place | Coordinate | tuple[float, float], *, limit: int = 10, kind: str | None = None, category: str | None = None, unit: str = 'km', include_origin: bool = False, origin_country: str | None = None) tuple[PlaceDistance, ...][source]
Return the places nearest to an origin, nearest first.
The origin can be a city name, any place or country model, a
Coordinate, or a(latitude, longitude)tuple. Filter withkindorcategory(category="water"finds the nearest lakes and rivers). Distances are great-circle surface measurements in"km","mi", or"nmi".- Parameters:
origin – A city or place name, a country (its capital), any model with coordinates, or a
(latitude, longitude)tuple.limit – The most places to return.
kind – Keep only this kind, such as
"volcano".category – Keep only this category, such as
"water".unit –
"km","mi", or"nmi".include_origin – Also list places named like the origin, at the origin.
origin_country – The country of
origin, when its name is shared.
- Returns:
PlaceDistancerows, nearest first.
Example
>>> atlas.places_near("Reykjavik", kind="volcano", limit=2) (PlaceDistance('Sundhnúkur, volcano (IS) · 38 km'), PlaceDistance('Lágafell, volcano (IS) · 42 km'))
- Atlas.heritage_sites_near(origin: str | Country | Capital | City | Place | Coordinate | tuple[float, float], *, limit: int = 10, category: str | None = None, unit: str = 'km') tuple[SiteDistance, ...][source]
Return the World Heritage sites nearest to a place, nearest first.
originis a city or place name, a country (its capital), a model with coordinates, or a(latitude, longitude)tuple.unitis"km"or"mi". Needs the landmarks pack.- Parameters:
origin – A city or place name, a country (its capital), any model with coordinates, or a
(latitude, longitude)tuple.limit – The most sites to return.
category – Keep only
"cultural","natural", or"mixed"sites.unit –
"km"or"mi".
- Returns:
SiteDistancerows, nearest first.
Example
>>> atlas.heritage_sites_near("Cusco", limit=1) (SiteDistance('Historic centre of Cusco, cultural · 1.9 km'),)
- Atlas.sun(where: str | Country | Capital | City | Place | Coordinate | tuple[float, float], on: date | None = None) SunTimes[source]
Return sunrise, sunset, day length, and the noon sun height for a place.
whereis a city or place name, a country (its capital), a model with coordinates, or a(latitude, longitude)tuple.ondefaults to today. Times are in UTC, and also on the local clock when the place is a city, capital, or country and the computer has time zone data (seeSunTimes). They agree with almanac times to about a minute between latitudes 72° north and south. Compareatlas.sun("Oslo", date(2026, 6, 21))with December to see why seasons happen.- Parameters:
where – A city or place name, a country (its capital), any model with coordinates, or a
(latitude, longitude)tuple.on – The day, or
Nonefor today.
- Returns:
SunTimesthat print as one sentence.
Example
>>> from datetime import date >>> print(atlas.sun((59.91, 10.75), date(2026, 6, 21))) # Oslo On 21 June 2026 the sun rises at 01:53 UTC and sets at 20:43 UTC, giving 18 h 50 min of daylight. At noon it is 54° above the horizon.
- Atlas.antipode(where: str | Country | Capital | City | Place | Coordinate | tuple[float, float], *, limit: int = 3) Antipode[source]
Return the point on the opposite side of the Earth, and the places nearest it.
Dig straight down through the centre of the Earth and you come out at the antipode: the latitude flips north and south, and the longitude moves halfway around the world.
whereis a city or place name, a country (its capital), a model with coordinates, or a(latitude, longitude)tuple. Most antipodes are at sea.nearestlists well-known places within 500 km of the antipode first, nearest first.- Parameters:
where – A city or place name, a country (its capital), any model with coordinates, or a
(latitude, longitude)tuple.limit – How many nearby places to list.
- Returns:
An
Antipodewith the opposite point and the places nearest it.
Example
>>> print(atlas.antipode("Madrid")) Straight through the centre of the Earth from 40.42° N, 3.70° W you would come out at 40.42° S, 176.30° E. The nearest well-known place is Waipatiki, town (NZ), 4.9 km away.
Borders
Who touches whom by land, and how to get there.
- Atlas.neighbors(country: str | Country) 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.
- Parameters:
country – A country name, code, or profile.
- Returns:
The neighboring
Countryprofiles, alphabetical.- Raises:
CountryNotFoundError – The country is unknown.
Example
>>> atlas.neighbors("Portugal") (Country(name='Spain', alpha2='ES'),) >>> atlas.neighbors("Japan") ()
Return whether two countries share a reviewed land border.
- Parameters:
country1 – A country name, code, or profile.
country2 – Another country.
- Returns:
Truewhen the two touch by land.
Example
>>> atlas.shares_border("France", "Spain") True >>> atlas.shares_border("France", "Portugal") False
Return alphabetized land neighbors shared by two countries.
- Parameters:
country1 – A country name, code, or profile.
country2 – Another country.
- Returns:
The
Countryprofiles that border both.
Example
>>> atlas.shared_neighbors("France", "Germany") (Country(name='Belgium', alpha2='BE'), Country(name='Luxembourg', alpha2='LU'), Country(name='Switzerland', alpha2='CH'))
- Atlas.border_path(origin: str | Country, destination: str | Country) 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.- Parameters:
origin – The starting country.
destination – The country to reach.
- Returns:
A
BorderPathResultthat prints as the route, orNone.
Example
>>> print(atlas.border_path("Portugal", "Poland")) Portugal → Spain → France → Germany → Poland (4 border crossings) >>> atlas.border_path("Japan", "France") is None True
- Atlas.border_crossings(origin: str | Country, destination: str | Country) int | None[source]
Return the fewest land-border crossings, or
Noneif unreachable.- Parameters:
origin – The starting country.
destination – The country to reach.
- Returns:
The number of borders crossed on the shortest land route.
Example
>>> atlas.border_crossings("Portugal", "Germany") 3 >>> atlas.border_crossings("Japan", "Iceland") is None True
- Atlas.has_land_route(origin: str | Country, destination: str | Country) 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.- Parameters:
origin – The starting country.
destination – The country to reach.
- Returns:
Truewhen you could walk from one to the other across borders.
Example
>>> atlas.has_land_route("Portugal", "Austria") True >>> atlas.has_land_route("Iceland", "Norway") False
- Atlas.countries_reachable_by_land(country: str | Country) 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.
- Parameters:
country – The starting country.
- Returns:
The other
Countryprofiles you could reach across borders.
Example
>>> len(atlas.countries_reachable_by_land("Portugal")) > 50 True >>> atlas.countries_reachable_by_land("Japan") ()
Learn
Quizzes, flashcards, and a short tour.
- Atlas.quiz(topic: Literal['closer_to_equator', 'higher', 'kinds'], *, count: int = 5, choices: int = 4, continent: str | None = None, region: str | None = None, seed: int | str = 0) tuple[PlaceQuestion, ...][source]
- Atlas.quiz(topic: str, *, count: int = 5, choices: int = 4, continent: str | None = None, region: str | None = None, seed: int | str = 0) tuple[QuizQuestion, ...]
Build multiple-choice questions from sourced facts.
- Parameters:
topic – A country topic from
learning_topics(), such as"capitals"or"flags", or a place topic fromPLACE_QUIZ_TOPICS:"higher"(which mountain is higher?),"kinds"(what kind of place is it?), or"closer_to_equator".count – How many questions to make.
choices – Answers per country question, from 2 through 6. Place questions come with their own choices.
continent – Ask only about countries on this continent.
region – Ask only about countries in this region or subregion.
seed – The same seed always gives the same questions, choices, and answer positions, on every supported Python version.
- Returns:
QuizQuestionrows for country topics, orPlaceQuestionrows for place topics. Each prints as the question with numbered choices.- Raises:
ValueError – The topic is unknown, or the filters leave too few distinct answers for the requested number of choices.
No scoring, learner data, or session state is stored.
Example
>>> question = atlas.quiz("capitals", count=1, region="Western Europe")[0] >>> print(question) What is the capital of Switzerland? 1) Monaco 2) Bern 3) Amsterdam 4) Berlin >>> question.answer 'Bern' >>> print(atlas.quiz("higher", count=1, seed=7)[0]) Which is higher: Mauna Loa or Weisshorn? 1) Mauna Loa 2) Weisshorn
- Atlas.flashcards(topic: str, *, count: int = 10, 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,driving_sides,flags,highest_points,language_codes,lakes,local_names,m49_codes,mains_electricity,neighbors,plug_types,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.
- Parameters:
topic – A topic from
learning_topics(), such as"capitals".count – How many cards to make.
continent – Use only countries on this continent.
region – Use only countries in this region or subregion.
seed – The same seed always gives the same cards.
- Returns:
Flashcardrows that print as the prompt and its answer.- Raises:
ValueError – The topic is unknown or
countis too large.
Example
>>> card = atlas.flashcards("capitals", count=1, region="Western Europe")[0] >>> print(card) What is the capital of Switzerland? Bern >>> card.answer 'Bern'
- Atlas.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.
- Returns:
Topic names such as
"capitals"and"flags".
Example
>>> atlas.learning_topics()[:4] ('alpha_2_codes', 'alpha_3_codes', 'areas', 'border_counts')
Numbers and maps
World Bank statistics, world maps, and 3D country maps. These need the statistics or a map pack.
- Atlas.indicators() tuple[Indicator, ...][source]
Return every statistic in the statistics pack, such as
life_expectancy.Needs the statistics pack (
pyworldatlas get statistics).- Returns:
Every
Indicator, with its unit and source.- Raises:
PackNotInstalledError – The statistics pack is not installed.
Example
>>> len(atlas.indicators()) 11 >>> atlas.indicators()[0] Indicator(key='birth_rate', unit='per 1,000 people a year')
- Atlas.statistic(country: str | Country, indicator: str, year: int | None = None) StatisticValue | None[source]
Return one published value, the latest unless
yearis given.Returns
Nonewhen the publisher has no value; missing values are never estimated. Needs the statistics pack.- Parameters:
country – A country name, code, or profile, or
"world".indicator – A key from
indicators().year – The year to read, or
Nonefor the latest.
- Returns:
A
StatisticValue, orNone.
Example
>>> print(atlas.statistic("Brazil", "urban_population", 1960)) 44.7% of people (1960)
- Atlas.time_series(country: str | Country, indicator: str) StatisticSeries[source]
Return the yearly values of an indicator for a country, from 1960.
countryis a country name, code, or profile, or"world"for the World Bank’s world total. Years without a published value areNone. Needs the statistics pack (pyworldatlas get statistics).- Parameters:
country – A country name, code, or profile, or
"world".indicator – A key from
indicators(), such as"life_expectancy".
- Returns:
A
StatisticSerieswith asummarysentence.- Raises:
ValueError – The indicator is unknown.
PackNotInstalledError – The statistics pack is not installed.
Example
>>> print(atlas.time_series("Kenya", "electricity_access").summary) Access to electricity in Kenya rose from 10.9% of people in 1993 to 77.0% of people in 2024.
- Atlas.world_map(indicator: str, *, year: int | None = None) WorldMap[source]
Return a world map with every country colored by one indicator.
Each country shows its value for
year, or its latest value whenyearisNone. Countries fall into five classes with about the same number of countries each; the colors order the numbers and say nothing about which is better. Callshow()to open the map,write_html()orwrite_svg()to save it, or display it in a notebook. Needs the statistics pack and a map pack (pyworldatlas get statisticsandpyworldatlas get maps-lite).- Parameters:
indicator – A key from
indicators().year – The year to show, or
Nonefor each country’s latest.
- Returns:
A
WorldMap.
Example
>>> print(atlas.world_map("life_expectancy", year=2020)) Life expectancy at birth (years), in 2020
- Atlas.map(country: str | Country, *, quality: str = 'auto', places: int = 8) 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 map marks the
placesbest-known towns, mountains and islands, lakes and seas, and landmarks of the country, each kind as a layer that can be shown or hidden. Passplaces=0for terrain only.The returned map opens in the default browser when its
show()method is called. Maps need a map pack, installed once withpyworldatlas get maps(Standard) orpyworldatlas get maps-lite(Overview). Packs are read from this atlas’sdata_dir.- Parameters:
country – A country name, code, or profile.
quality –
"auto","standard", or"overview".places – How many well-known places to mark.
- Returns:
A
CountryMap.- Raises:
MapSupportNotInstalledError – No map pack is installed.
Example
>>> japan = atlas.map("Japan") >>> print(japan) 3D map of Japan
- Atlas.sort_by_statistic(indicator: str, *, year: int | None = None, descending: bool = True, limit: int | None = 10) tuple[StatisticValue, ...][source]
List countries sorted by one indicator, for a year or each one’s latest.
Sorting only orders the published numbers; it says nothing about which is better. Countries without a value are left out. Needs the statistics pack.
rank()gives the same order as numbered rows with country names; prefer it in new code.- Parameters:
indicator – A key from
indicators().year – The year to compare, or
Nonefor each country’s latest.descending –
Falsesorts smallest first.limit – The most rows to return, or
Nonefor all.
- Returns:
StatisticValuerows, sorted.
Example
>>> atlas.sort_by_statistic("forest_area", limit=2) (StatisticValue(indicator='forest_area', area='FM', year=2024, value=92.1), StatisticValue(indicator='forest_area', area='SR', year=2024, value=91.5))
Landmarks
Airports and UNESCO World Heritage sites. These need the landmarks pack.
- Atlas.airport(code: str) Airport[source]
Return the airport with this IATA (
"LHR") or ICAO ("EGLL") code.Needs the landmarks pack (
pyworldatlas get landmarks). RaisesPlaceNotFoundErrorfor an unknown code.- Parameters:
code – A three-letter IATA or four-letter ICAO code.
- Returns:
The
Airport.
Example
>>> atlas.airport("LHR") Airport(iata_code='LHR', name='London Heathrow Airport')
- Atlas.airports(country: str | Country | None = None, *, size: str | None = None) tuple[Airport, ...][source]
Return airports with scheduled flights, largest first, then by name.
Narrow with
countryandsize("large","medium", or"small"). Needs the landmarks pack (pyworldatlas get landmarks).- Parameters:
country – Keep only airports in this country.
size – Keep only
"large","medium", or"small"airports.
- Returns:
Airportrecords.
Example
>>> atlas.airports("Iceland", size="medium")[:2] (Airport(iata_code='EGS', name='Egilsstaðir Airport'), Airport(iata_code='GRY', name='Grímsey Airport'))
- Atlas.world_heritage_site(query: str | int) WorldHeritageSite[source]
Return one World Heritage site by list number or name.
Names match without regard to case or accents: an exact name first, then the one site whose name contains the query. Raises
PlaceNotFoundErrororAmbiguousPlaceError.- Parameters:
query – The site’s list number, or its name or part of it.
- Returns:
The
WorldHeritageSite.
Example
>>> atlas.world_heritage_site("Machu Picchu") WorldHeritageSite(site_id=274, name='Historic Sanctuary of Machu Picchu')
- Atlas.world_heritage_sites(*, category: str | None = None) tuple[WorldHeritageSite, ...][source]
Return UNESCO World Heritage sites in list order.
Narrow with
category("cultural","natural", or"mixed"). Useheritage_sites_near()to find the sites around a place. Needs the landmarks pack (pyworldatlas get landmarks).- Parameters:
category – Keep only
"cultural","natural", or"mixed"sites.- Returns:
WorldHeritageSiterecords.
Example
>>> atlas.world_heritage_sites(category="mixed")[0] WorldHeritageSite(site_id=39, name='Ngorongoro Conservation Area')
The atlas itself
Versions, and closing the database.
- Atlas.dataset_info() DatasetInfo[source]
Return the installed library, database schema, and dataset versions.
Record these values when a lesson or calculation must be reproducible.
- Returns:
A
DatasetInfowith versions, build date, and source names.
Example
>>> print(atlas.dataset_info()) PyWorldAtlas ..., 248 countries >>> atlas.dataset_info().country_count 248
- Atlas.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.Example
>>> other = Atlas() >>> other.close() >>> other.close() # closing twice is safe
Older names
These still work and return the same results, but will be removed in 1.0. See Newer names.
- Atlas.nearest_capitals(*args: Any, **kwargs: Any) tuple[CapitalDistance, ...][source]
Older name for
capitals_near(), kept until 1.0.
- Atlas.nearest_cities(*args: Any, **kwargs: Any) tuple[CityDistance, ...][source]
Older name for
cities_near(), kept until 1.0.
- Atlas.world_heritage_sites_near(*args: Any, **kwargs: Any) tuple[SiteDistance, ...][source]
Older name for
heritage_sites_near(), kept until 1.0.
- Atlas.lookup(query: str, *, limit: int = 10) tuple[Country | Place, ...][source]
Older name for
find(), kept until 1.0.
- Atlas.place_quiz(topic: str, *, count: int = 5, seed: int | str = 0) tuple[PlaceQuestion, ...][source]
Older name for
quiz(topic)with a place topic, kept until 1.0.
- Atlas.countries_with_river(name: str | None = None) tuple[Country, ...][source]
Older name for
countries(river=name), kept until 1.0.With no
nameit iscountries(has_rivers=True).
- Atlas.countries_with_lake(name: str | None = None) tuple[Country, ...][source]
Older name for
countries(lake=name), kept until 1.0.With no
nameit iscountries(has_lakes=True).
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().
- property summary: SummaryText
Return a readable, multiline introduction to this country profile.
print(country.summary)shows useful classroom facts and leaves out unavailable values. To show the local name in a particular language, call it with a language code:country.summary(local_language="fr"). Without one, the selected non-English local identity is used when present. This is for reading; useto_dict()when field names and machine-readable values matter.
- __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, travel: TravelBasics | 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, 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.TravelBasics[source]
Everyday facts a visitor needs: plugs, mains electricity, and driving side.
plug_typesare IEC World Plugs letters such as"A"or"G".voltages_vandfrequencies_hzlist the household mains supply; a country can use more than one.driving_sideis"left"or"right", orNonewhen the source does not agree on one side.- property summary: str
Return one readable line, such as
"Plugs A, B · 100 V, 50/60 Hz · drives on the left".
- __init__(plug_types: tuple[str, ...], voltages_v: tuple[int, ...], frequencies_hz: tuple[int, ...], driving_side: str | None, 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.- property country_code: str
Return the two-letter code, the same value other results call
country_code.
- __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) 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('climate unknown'), 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('area unknown'), landlocked: bool | None = None, physical: PhysicalGeography = PhysicalGeography(coastline_km=None, highest_point=None, rivers=0, lakes=0)) 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, population: int | None = None, elevation_m: float | None = None, timezone_id: str | None = None, 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, 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, ...] = (), geonames_id: int | None = None) None
Place is any named place on Earth from the school atlas or an installed
place pack; see Every place on Earth.
- class pyworldatlas.Place[source]
Any named place on Earth: a town, mountain, lake, ruin, island, and more.
Places come from the GeoNames gazetteer.
kindis a plain-English label such as"mountain"andcategoryits general group such as"landform".english_nameequalsnameunless the place has a different English name ("Lago Titicaca"is"Lake Titicaca").fame(0 to 255) estimates how widely a place is known and orders search results; it is not a measure of importance.- property label: str
Return a compact label such as
"Lake Titicaca, lake (PE)".
- __init__(name: str, english_name: str, kind: str, category: str, country_code: str, coordinates: Coordinate, population: int | None = None, elevation_m: int | None = None, feature_code: str = '', fame: int = 0) 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.
sourcenames where the value comes from, such as"GeoNames country population snapshot". Different sources can disagree: the statistics pack’s World Bank population (atlas.rank("population", year=2020)) is newer and dated by year.yearis the year of a statistic, andNonefor profile metrics such as area.- __init__(position: int, country: CountryReference, metric: str, value: int | float, unit: str, source: str | None = None, year: int | None = None) 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.cities_near().- 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.Airport[source]
An airport with scheduled passenger flights, from OurAirports.
iata_codeis the three-letter code on tickets and bags ("LHR");icao_codethe four-letter code pilots use ("EGLL").sizeis"large","medium", or"small".country_codeis the two-letter code as published by OurAirports.- property label: str
Return a compact label such as
"LHR · London Heathrow Airport (GB)".
- __init__(iata_code: str, icao_code: str | None, name: str, municipality: str | None, country_code: str, coordinates: Coordinate, elevation_m: int | None, size: str) None
- class pyworldatlas.WorldHeritageSite[source]
A site on the UNESCO World Heritage List, from Wikidata.
site_idis the list number.categoryis"cultural","natural", or"mixed"from the site’s selection criteria.coordinatesmarks one representative point andinscribedthe year the site was added, when known. Find sites by name, number, category, or distance from any place.- property label: str
Return a compact label such as
"Taj Mahal, cultural".
- __init__(site_id: int, name: str, coordinates: Coordinate | None, inscribed: int | None, category: str | None) None
- class pyworldatlas.SiteDistance[source]
A World Heritage site and its great-circle distance from an origin.
- to_json(indent: int | None = None) str[source]
Serialize this nearby-site result without escaping Unicode text.
- __init__(site: WorldHeritageSite, distance: float, unit: str) None
- class pyworldatlas.Antipode[source]
The point on the exact opposite side of the Earth from an origin.
nearestlists well-known places within 500 km of the antipode first, then other places, each group nearest first. Most antipodes are at sea, so the nearest place can be far away.- property summary: str
Return a plain-language description of the antipode.
- __init__(origin: Coordinate, antipode: Coordinate, nearest: tuple[PlaceDistance, ...]) None
- class pyworldatlas.PlaceQuestion[source]
A deterministic multiple-choice question about famous places.
placesholds the places the question is about, so a learner can look up more after answering. Choices are in display order andansweris always one of them.- property answer_number: int
Return the correct choice number, counting from one.
- is_correct(response: str | int) bool[source]
Check a displayed answer (case-insensitive) or a one-based choice number.
- class pyworldatlas.Indicator[source]
One statistic, such as life expectancy, with its unit and source.
keyis the short name used by the atlas ("life_expectancy") andcodethe World Bank indicator code ("SP.DYN.LE00.IN").- __init__(key: str, name: str, unit: str, code: str, source: str, decimals: int = 1) None
- class pyworldatlas.StatisticSeries[source]
Yearly values of one indicator for one country, or
"world".valuesruns fromfirst_yearone year at a time; a year the publisher has no value for isNoneand is never filled in.- property country_code: str | None
Return the two-letter country code, or
Nonefor the world total.
- property last_year: int
Return the last year in the series.
- property points: tuple[tuple[int, float], ...]
Return
(year, value)pairs for every year with a value.
- property latest: StatisticValue | None
Return the most recent published value.
- sparkline(width: int = 30) str[source]
Return a one-line text chart, such as
"▁▂▃▄▅▆▇█".The series is shown in at most
widthsteps, each the average of its years; years with no value show as a space.
- property summary: str
Return a plain-language sentence about the first and latest values.
- class pyworldatlas.StatisticValue[source]
One published value: an indicator for a country (or the world) in a year.
- property country_code: str | None
Return the two-letter country code, or
Nonefor the world total.
- class pyworldatlas.SunTimes[source]
Sunrise, sunset, and daylight for one place on one date.
sunrise,sunset, andsolar_noonare in UTC. When the place’s time zone is known (timezone_id, such as"Europe/Paris") and the computer has time zone data,local_sunriseandlocal_sunsetgive the local clock times and the summary uses them.sunriseandsunsetareNoneduring the midnight sun (day length 24 hours) and the polar night (day length 0). A UTC time can fall on the day before or afterdatefar from Greenwich.noon_sun_heightis the sun’s angle above the horizon at solar noon, in degrees; it is negative when the sun stays below the horizon.- property local_sunrise: datetime | None
Return sunrise on the local clock, or
Nonewhen the time zone is unknown.
- property local_sunset: datetime | None
Return sunset on the local clock, or
Nonewhen the time zone is unknown.
- property daylight: str
Return the day length as text, such as
"16 h 38 min".
- property summary: str
Return a plain-language description of the day.
- __init__(coordinates: Coordinate, date: date, solar_noon: datetime, sunrise: datetime | None, sunset: datetime | None, day_length_hours: float, noon_sun_height: float, timezone_id: str | None = None) None
- class pyworldatlas.PlaceDistance[source]
A nearby place and its great-circle distance from an origin.
unitrecords the unit requested frompyworldatlas.Atlas.places_near().
- 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
Newer names
Version 0.13 gave every method the same naming style. The older names still work and return exactly the same results, so existing code keeps running. They will be removed in 1.0, so new code should use the newer names.
Older name |
Newer name |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
New to the atlas? atlas.help() prints a short
tour of things to try, and pyworldatlas tour prints it on the command line.
Printing results
Every result prints as one readable line, such as
CountryRanking('#1 Canada: 202,080 km'). Call
pyworldatlas.show_details() to print every field instead, or set the
environment variable PYWORLDATLAS_DETAILS=1. Details change only how
results print; to_dict() always returns every field.
import pyworldatlas
with pyworldatlas.show_details():
print(repr(atlas.rank("area", limit=1)[0]))
- class pyworldatlas.show_details[source]
Print every field of a result instead of the short one-line form.
show_details()turns details on,show_details(False)turns them off, andwith show_details(): ...turns them on only inside the block.>>> import pyworldatlas >>> with pyworldatlas.show_details(): ... pass
- classmethod __new__(*args, **kwargs)
- class pyworldatlas.Distance[source]
A great-circle distance that is still a plain number.
Distancebehaves exactly like afloat(add it, compare it, round it, or save it to JSON), and also remembers itsunit. Printing it gives friendly text such as"9,713 km"; distances under 10 keep one decimal, such as"0.3 km".>>> from pyworldatlas import Distance >>> distance = Distance(9712.518, "km") >>> print(distance) 9,713 km >>> distance > 9000 True
- property text: str
Return the distance as friendly text, such as
"9,713 km".
- __init__()
- class pyworldatlas.models.units.SummaryText[source]
Text that can also be called, so
country.summaryandcountry.summary()both work.Summaries are properties on every result. Country summaries used to be a method; calling one still works, and
country.summary(local_language="fr")still chooses which local name to show.- static __new__(cls, text: str, build: Callable[[...], str]) SummaryText[source]
- __init__()
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 exact match.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
- exception pyworldatlas.AmbiguousCountryError[source]
Raised when an exact country name identifies multiple profiles.
- 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)
- exception pyworldatlas.CapitalNotFoundError[source]
Raised when a capital query has no match.
- classmethod __new__(*args, **kwargs)
- __init__(*args, **kwargs)
Optional maps
Maps read their data from an installed map pack (pyworldatlas get maps or
pyworldatlas get maps-lite). See Interactive 3D maps before depending on the
experimental map API.
- class pyworldatlas.maps.CountryMap[source]
A lazily loaded interactive 3D country map.
Use
show()to open a standalone offline browser view,write_html()to save one, orto_dict()for the plain plotly.js figure data.- places: tuple[tuple[str, str, str, float, float, int | None], ...]
The places to mark, each as name, kind, category, latitude, longitude, and elevation in metres.
- classmethod from_country(country: object, *, quality: str = 'auto', data_dir: str | Path | None = None, places: tuple[Any, ...] = ()) CountryMap[source]
Create a map request from a PyWorldAtlas country profile.
placesarePlaceobjects to mark on the map.
- 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.
- to_dict() dict[str, Any][source]
Return the figure as plain plotly.js
dataandlayoutdictionaries.The figure contains elevation and climate surface controls, terrain height choices, optional river and capital labels, a country outline, source-provided river centerlines, the primary capital when coordinates are available, and markers for well-known places.
- figure() Any[source]
Return a
plotly.graph_objects.Figurefor notebooks and customization.This is the only map feature that needs the separate
plotlypackage (pip install plotly). Every other method works without it.
- to_html(*, auto_rotate: bool = False, rotation_speed: float = 1.0) str[source]
Return a complete standalone HTML page with plotly.js embedded.
The page fills the browser window and offers a control panel to color the terrain by elevation or climate, change terrain height, show or hide the capital, rivers, river names, and each kind of marked place, rotate the view, reset the camera, and download a high-resolution PNG. The map can be turned, tilted, and zoomed from the keyboard, carries a plain-language description for screen readers, and announces each change. On narrow screens the panel becomes a collapsible bottom sheet, and it follows the reader’s light or dark color scheme. Set
auto_rotate=Trueto begin rotating when the page opens.rotation_speedaccepts values from0.25through3;1completes a turn in about twenty seconds.
- __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', data_dir: str | None = None, places: tuple[tuple[str, str, str, float, float, int | None], ...] = ()) None
- 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.
- class pyworldatlas.maps.WorldMap[source]
A world map with every country colored by one statistic.
Countries fall into five classes that each hold about the same number of countries, from light (smaller numbers) to dark (larger numbers). The colors order the published numbers only; they do not say which is better. Countries without a value are hatched and labelled “No data”.
- values: tuple[StatisticValue, ...]
The value drawn for each country, in alphabetical order of country name.
- names: tuple[tuple[str, str], ...]
Every country on the map as
(alpha2, name), alphabetical by name.
- year: int | None
The requested year, or
Nonefor each country’s latest value.
- database: str
The map pack file the outlines are read from.
- property title: str
Return the map title, such as
"Life expectancy at birth (years), latest year".
- property class_edges: tuple[float, ...]
Return the boundaries between color classes, lowest first.
- to_svg() str[source]
Return the map as a standalone SVG image with a title, legend, and source line.
Each country carries a hover title with its value and year. The image follows the reader’s light or dark color scheme.
- __init__(indicator: Indicator, values: tuple[StatisticValue, ...], names: tuple[tuple[str, str], ...], year: int | None, database: str) None
- to_html() str[source]
Return a complete offline HTML page with the map and a table of every value.
The table lists each country in alphabetical order with its value and year, so the map can be read without seeing it.
Data packs
Install and locate optional PyWorldAtlas data packs.
A data pack is a .pack file (an uncompressed zip archive) that holds extra
offline data, such as the 3D map editions. Packs are published as files on the
project’s GitHub releases. Each library release pins the SHA-256 checksum of
every pack it accepts, so a modified, damaged, or mismatched file is refused.
Normal use never touches the network. Only get() (pyworldatlas get)
downloads, and only when it is called explicitly. Packs can also be installed
from a local file with add(), for example on a machine without internet.
Packs are stored in one folder, chosen in this order:
the
data_dirargument (also accepted bypyworldatlas.Atlas);the
PYWORLDATLAS_DATAenvironment variable;a per-user folder:
%LOCALAPPDATA%\PyWorldAtlas\packson Windows,~/Library/Application Support/PyWorldAtlas/packson macOS, and$XDG_DATA_HOME/pyworldatlas/packs(default~/.local/share) elsewhere.
- pyworldatlas.packs.get(name: str, path: str | Path | None = None, *, progress: Callable[[int, int], None] | None = None) InstalledPack[source]
Download one pack from this release on GitHub, verify it, and install it.
progressis called with(downloaded_bytes, total_bytes)while the file downloads. This is the only function in PyWorldAtlas that uses the network.
- pyworldatlas.packs.add(file: str | Path, path: str | Path | None = None) InstalledPack[source]
Install a pack from a local
.packfile and return it.The file’s SHA-256 checksum must match one of the packs this release pins, so only official, unmodified packs are accepted. An existing copy of the same pack is replaced.
- pyworldatlas.packs.installed(path: str | Path | None = None) tuple[InstalledPack, ...][source]
Return the packs installed in a pack folder, by name.
- pyworldatlas.packs.available() tuple[PackInfo, ...][source]
Return every pack this library release can install, by name.
- pyworldatlas.packs.remove(name: str, path: str | Path | None = None) bool[source]
Delete an installed pack. Return
Falsewhen it was not installed.
- pyworldatlas.packs.pack_path(name: str, path: str | Path | None = None) Path | None[source]
Return the folder of an installed pack, or
Noneif it is missing.
- pyworldatlas.packs.data_dir(path: str | Path | None = None) Path[source]
Resolve the pack folder from
path,PYWORLDATLAS_DATA, or the default.
- pyworldatlas.packs.default_data_dir() Path[source]
Return the per-user pack folder used when no other folder is given.
- class pyworldatlas.packs.PackInfo[source]
One data pack this library release accepts.
- property url: str
Return the GitHub release download address for this pack.
- __init__(name: str, title: str, file: str, sha256: str, size_bytes: int) 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
cities_near() 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.