Settings, errors and the low-level layer

Settings

configure(*, base_url='https://unsd-datacommons.gcp.un-icc.cloud', timeout=30.0, retries=3, cache=False, cache_hours=24)[source]

Change how undata connects, and forget anything it has cached in memory.

Parameters:
  • base_url (str) – Root of the Data Commons deployment.

  • timeout (float) – Seconds to wait for each response. Raise it on a slow connection.

  • retries (int) – How many times to retry a request that failed for a temporary reason.

  • cache (bool | str | Path) – Keep responses on disk and reuse them: True for the usual cache folder, or a folder of your choice. Useful on a slow or unreliable connection, and for notebooks that run again and again.

  • cache_hours (float) – How long a cached response is reused before asking again.

Example

>>> import undata as un
>>> un.configure(timeout=60)
clear_cache()[source]

Delete every response cached on disk. Returns how many were deleted.

Example

>>> import undata as un
>>> un.clear_cache()
42

Errors

Every error undata raises is an undata.UNDataError, with a message that says what to do next.

exception UNDataError[source]

Base class for every error this package raises.

exception PlaceNotFoundError(name, suggestions=())[source]

A country or region name was not recognised.

undata never substitutes a different place for one it does not recognise.

name

What was asked for.

suggestions

Close matches, best first. May be empty.

exception AmbiguousPlaceError(name, suggestions)[source]

A name matches more than one country, so undata will not pick one.

exception IndicatorNotFoundError(name, suggestions=(), *, phrase)[source]

An indicator id was not recognised, or a phrase was given instead of an id.

name

What was asked for.

suggestions

Indicator ids from a search for it, best first. May be empty.

exception AmbiguousIndicatorError(name, options)[source]

An SDG indicator number is reported by several series, so undata will not pick one.

name

The SDG indicator number asked for.

suggestions

The ids of the series that report it.

exception ConnectionFailedError(message, *, url)[source]

The request never reached the API, or no response arrived in time.

exception APIError(message, *, status, url, body)[source]

The API answered with an HTTP error status.

status

The HTTP status code.

url

The full request URL, query string included.

body

The first 500 characters of the response body.

exception BlockedRequestError(message, *, status, url, body)[source]

The deployment’s firewall refused the request before the API saw it.

data.un.org needs no API key, so a 403 is never an authentication problem. Two request shapes are known to trigger it: a POST body containing a line break, and a POST body containing a "select" key. undata avoids both; seeing this error means the firewall’s rules have changed, and an issue would be very welcome.

Warnings

Data problems are warnings, so the table still comes back. Turn them into errors with warnings.simplefilter("error", un.UNDataWarning), or silence one kind with warnings.simplefilter("ignore", un.MixedYearsWarning).

exception UNDataWarning[source]

Base class for every warning this package raises.

exception MissingDataWarning[source]

Some of the countries you asked for have no data for an indicator.

Missing data is left out of the table, never filled with zero.

exception MixedYearsWarning[source]

The “latest” values come from different years, so compare them with care.

exception StaleDataWarning[source]

Values older than the since year you set were left out of the table.

exception CoverageWarning[source]

Not every country has data for every indicator you are comparing.

exception PlaceGuessedWarning[source]

data.un.org’s search chose a place your question did not name.

The low-level layer

For developers: the network client and the identifier grammar the friendly functions are built on.

class Transport(*, base_url='https://unsd-datacommons.gcp.un-icc.cloud', timeout=30.0, retries=3, http_client=None, cache_dir=None, cache_hours=24)[source]

A synchronous HTTP transport with retries, explanatory errors and a disk cache.

Parameters:
  • base_url (str) – Root of the Data Commons deployment.

  • timeout (float) – Seconds to wait for each response.

  • retries (int) – How many times to retry a 429, 502, 503 or 504, or a dropped connection, before giving up.

  • http_client (httpx.Client | None) – An httpx.Client to use instead of creating one. Useful for proxies, custom certificates, and tests.

  • cache_dir (str | Path | None) – Keep successful responses here and reuse them, so a notebook that runs again does not ask again. None turns the cache off.

  • cache_hours (float) – How long a cached response stays fresh.

DEFAULT_BASE_URL

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

parse_dcid(dcid)[source]

Parse a variable dcid into its parts.

Returns None rather than raising for anything that is not a path of three or more segments, such as Count_Person or country/BGD, so callers can treat unfamiliar identifiers as opaque on a graph that is still growing.

Parameters:

dcid (str) – A variable identifier, such as "undata/sdg/SH_STA_MORT.SEX--F".

Returns:

Its namespace, agency, code and dimensions, or None.

Return type:

ParsedDcid | None

Example

>>> parsed = parse_dcid("undata/sdg/VC_DTH_TOTN.AGE--Y0T17__SEX--F")
>>> parsed.code, [str(d) for d in parsed.dimensions]
('VC_DTH_TOTN', ['AGE--Y0T17', 'SEX--F'])
>>> parsed.base
'undata/sdg/VC_DTH_TOTN'
>>> parse_dcid("Count_Person") is None
True
build_dcid(base, dimensions=None)[source]

Build a variable dcid from its base and dimension filters.

Dimensions are sorted by name, as they are in the graph’s own identifiers, so the same slice always produces the same identifier whatever order you pass them in.

Parameters:
  • base (str) – The series without dimensions, such as "undata/sdg/VC_DTH_TOTN".

  • dimensions (Mapping[str, str] | None) – Dimension codes and values, such as {"SEX": "F"}.

Returns:

The identifier of that slice.

Return type:

str

Example

>>> build_dcid("undata/sdg/VC_DTH_TOTN", {"SEX": "F", "AGE": "Y0T17"})
'undata/sdg/VC_DTH_TOTN.AGE--Y0T17__SEX--F'
describe_dcid(dcid)[source]

Return a short human-readable gloss of a dcid.

Parameters:

dcid (str) – Any identifier; ones undata cannot parse come back unchanged.

Returns:

The agency, code and slice in words.

Return type:

str

Example

>>> describe_dcid("undata/sdg/SH_STA_MORT.SEX--F")
'Global SDG Indicators Database · SH_STA_MORT [SEX=F]'
child_countries_of(place)[source]

Return the relation expression for every country inside place.

<-containedInPlace+ walks containment inward and recursively, so one request covers a whole continent; {typeOf:Country} keeps other place types out.

Parameters:

place (str) – A platform place identifier, such as "africa" or "SouthernAsia".

Returns:

The expression to pass where the API takes a place relation.

Return type:

str

Example

>>> child_countries_of("africa")
'africa<-containedInPlace+{typeOf:Country}'