The cleopatra.config module gathers cleopatra's cross-cutting, user-facing settings in
one discoverable place: an opt-in matplotlib-backend helper and the on-disk cache
directory used for downloaded basemap assets. Importing cleopatra does not change
the backend on its own — picking a backend is the application's job, not a library's.
Call Config.set_matplotlib_backend() yourself if you want cleopatra to choose a sensible
one for you: %matplotlib inline inside a Jupyter notebook (or %matplotlib notebook
when interactive=True), otherwise Agg in a plain script. You can also pass an explicit
backend name. set_matplotlib_backend is a staticmethod, so Config.set_matplotlib_backend(...)
works without an instance. Note that switching the backend closes any open figures — that
is matplotlib's behaviour — so call it before you start plotting.
fromcleopatra.configimportConfigConfig.set_matplotlib_backend("Agg")# explicitConfig.set_matplotlib_backend()# auto: inline in notebooks, Agg otherwise
Config.get_cache_dir() resolves where cleopatra caches the basemap assets it downloads —
the Natural Earth vectors and hypsometric relief used by
cleopatra.basemap.reference. It is the discoverable home for that
setting, resolved in this order: an explicit path argument, then the
CLEOPATRA_CACHE_DIR environment variable, then the default ~/.cleopatra/naturalearth.
A leading ~ is expanded. The getter only resolves the path — it does not create the
directory (the download helpers create it on first use), so it is safe to call just to
discover where the cache lives.
fromcleopatra.configimportConfigConfig.get_cache_dir()# ~/.cleopatra/naturalearth (default)# or set CLEOPATRA_CACHE_DIR=/data/cleopatra to override, or:Config.get_cache_dir("/data/cleopatra")# explicit override
Config gathers the package's cross-cutting, user-facing settings in one
discoverable place:
Config.set_matplotlib_backend — opt-in matplotlib backend selection.
Importing cleopatra does not change the active backend; picking one
is the application's responsibility, not a library's.
Config.get_cache_dir — where cleopatra caches downloaded basemap
assets. Resolves an explicit argument, then the CLEOPATRA_CACHE_DIR
environment variable, then the default ~/.cleopatra/naturalearth; it
only resolves the path and does not create the directory.
classConfig:"""Configuration helpers for the cleopatra package."""def__init__(self):pass@staticmethoddefset_matplotlib_backend(backend:str|None=None,interactive:bool=False)->str:"""Switch the active matplotlib backend (opt-in helper). cleopatra does not call this automatically. It is provided for users who want a one-liner to pick a backend. Switching the backend **closes every currently-open figure** — that is matplotlib's behaviour, not cleopatra's — so call this before you start plotting. Args: backend: Backend name to switch to (e.g. `"Agg"`, `"TkAgg"`, `"Qt5Agg"`). If `None`, an environment-appropriate default is chosen: `%matplotlib inline` inside a Jupyter notebook (or `%matplotlib notebook` when `interactive` is `True`), otherwise `"Agg"`. interactive: When `backend` is `None` and running inside a Jupyter notebook, use the interactive notebook backend instead of inline. Ignored otherwise. Default `False`. Returns: str: The name of the backend that is now active. """importmatplotlib.pyplotaspltifbackend:plt.switch_backend(backend)logger.info("Matplotlib backend set to %s",backend)elifis_notebook():fromIPythonimportget_ipythonmagic="notebook"ifinteractiveelse"inline"get_ipython().run_line_magic("matplotlib",magic)logger.info("Matplotlib set to %%matplotlib %s for Jupyter",magic)else:plt.switch_backend("Agg")logger.info("Matplotlib backend set to Agg (non-interactive)")returnmatplotlib.get_backend()@staticmethoddefget_cache_dir(path:str|os.PathLike|None=None)->Path:"""Resolve the directory cleopatra caches downloaded basemap assets in. This is the single, discoverable home for cleopatra's on-disk cache setting — the Natural Earth vectors and hypsometric relief downloaded by `cleopatra.basemap.reference`. Resolution order: 1. a non-empty explicit `path` argument; 2. the `CLEOPATRA_CACHE_DIR` environment variable, if set; 3. the default `~/.cleopatra/naturalearth`. A `path` (or `CLEOPATRA_CACHE_DIR` value) that is `None`, empty, or whitespace-only is treated as "not provided" and falls through to the next source, so `get_cache_dir("")` and `get_cache_dir(" ")` behave like `get_cache_dir()`. Note that `Path("")` is `Path(".")` under pathlib (indistinguishable from the current directory), so a `Path("")` argument resolves to `.`, not the default — pass an empty *string* (or `None`), not `Path("")`, to fall through. A leading `~` is expanded. This function only **resolves** the path; it does not create the directory (the download helpers create it on first use), so it is safe to call just to discover where the cache lives. Args: path: An explicit cache directory to use, overriding the environment variable and the default. A value that is `None`, empty, or whitespace-only is treated as not provided. A relative path (from `path` or the environment variable) is kept relative and resolved against the current working directory when the directory is created. Default `None`. Returns: pathlib.Path: The resolved (not necessarily existing) cache directory. Examples: - An explicit `path` is resolved as given (and overrides everything else): ```python >>> from cleopatra.config import Config >>> Config.get_cache_dir("/data/cleopatra").as_posix() '/data/cleopatra' ``` - With no argument, the `CLEOPATRA_CACHE_DIR` environment variable is honoured: ```python >>> import os >>> from cleopatra.config import Config >>> os.environ["CLEOPATRA_CACHE_DIR"] = "/var/cache/cleopatra" >>> Config.get_cache_dir().as_posix() '/var/cache/cleopatra' >>> del os.environ["CLEOPATRA_CACHE_DIR"] ``` - An explicit argument wins over the environment variable, and the returned path composes into an asset path: ```python >>> import os >>> from cleopatra.config import Config >>> os.environ["CLEOPATRA_CACHE_DIR"] = "/ignored" >>> asset = Config.get_cache_dir("/data") / "ne_110m_coastline.geojson.gz" >>> asset.as_posix() '/data/ne_110m_coastline.geojson.gz' >>> del os.environ["CLEOPATRA_CACHE_DIR"] ``` See Also: cleopatra.basemap.reference: Downloads basemap assets into this directory (its private `_cache_dir` resolves the location through this method and creates the directory on first use). """candidate=os.fspath(path)ifpathisnotNoneelseNoneifcandidateisNoneornotcandidate.strip():candidate=os.environ.get("CLEOPATRA_CACHE_DIR")ifcandidateandcandidate.strip():returnPath(candidate).expanduser()returnPath.home()/".cleopatra"/"naturalearth"
Resolve the directory cleopatra caches downloaded basemap assets in.
This is the single, discoverable home for cleopatra's on-disk
cache setting — the Natural Earth vectors and hypsometric relief
downloaded by cleopatra.basemap.reference. Resolution order:
a non-empty explicit path argument;
the CLEOPATRA_CACHE_DIR environment variable, if set;
the default ~/.cleopatra/naturalearth.
A path (or CLEOPATRA_CACHE_DIR value) that is None, empty, or
whitespace-only is treated as "not provided" and falls through to
the next source, so get_cache_dir("") and get_cache_dir(" ")
behave like get_cache_dir(). Note that Path("") is Path(".")
under pathlib (indistinguishable from the current directory), so a
Path("") argument resolves to ., not the default — pass an empty
string (or None), not Path(""), to fall through. A leading ~
is expanded. This function only resolves the path; it does not
create the directory (the download helpers create it on first use),
so it is safe to call just to discover where the cache lives.
Parameters:
Name
Type
Description
Default
path
str | PathLike | None
An explicit cache directory to use, overriding the
environment variable and the default. A value that is
None, empty, or whitespace-only is treated as not
provided. A relative path (from path or the environment
variable) is kept relative and resolved against the current
working directory when the directory is created. Default
None.
None
Returns:
Type
Description
Path
pathlib.Path: The resolved (not necessarily existing) cache
Path
directory.
Examples:
An explicit path is resolved as given (and overrides
everything else):
cleopatra.basemap.reference: Downloads basemap assets into this
directory (its private _cache_dir resolves the location
through this method and creates the directory on first use).
@staticmethoddefget_cache_dir(path:str|os.PathLike|None=None)->Path:"""Resolve the directory cleopatra caches downloaded basemap assets in. This is the single, discoverable home for cleopatra's on-disk cache setting — the Natural Earth vectors and hypsometric relief downloaded by `cleopatra.basemap.reference`. Resolution order: 1. a non-empty explicit `path` argument; 2. the `CLEOPATRA_CACHE_DIR` environment variable, if set; 3. the default `~/.cleopatra/naturalearth`. A `path` (or `CLEOPATRA_CACHE_DIR` value) that is `None`, empty, or whitespace-only is treated as "not provided" and falls through to the next source, so `get_cache_dir("")` and `get_cache_dir(" ")` behave like `get_cache_dir()`. Note that `Path("")` is `Path(".")` under pathlib (indistinguishable from the current directory), so a `Path("")` argument resolves to `.`, not the default — pass an empty *string* (or `None`), not `Path("")`, to fall through. A leading `~` is expanded. This function only **resolves** the path; it does not create the directory (the download helpers create it on first use), so it is safe to call just to discover where the cache lives. Args: path: An explicit cache directory to use, overriding the environment variable and the default. A value that is `None`, empty, or whitespace-only is treated as not provided. A relative path (from `path` or the environment variable) is kept relative and resolved against the current working directory when the directory is created. Default `None`. Returns: pathlib.Path: The resolved (not necessarily existing) cache directory. Examples: - An explicit `path` is resolved as given (and overrides everything else): ```python >>> from cleopatra.config import Config >>> Config.get_cache_dir("/data/cleopatra").as_posix() '/data/cleopatra' ``` - With no argument, the `CLEOPATRA_CACHE_DIR` environment variable is honoured: ```python >>> import os >>> from cleopatra.config import Config >>> os.environ["CLEOPATRA_CACHE_DIR"] = "/var/cache/cleopatra" >>> Config.get_cache_dir().as_posix() '/var/cache/cleopatra' >>> del os.environ["CLEOPATRA_CACHE_DIR"] ``` - An explicit argument wins over the environment variable, and the returned path composes into an asset path: ```python >>> import os >>> from cleopatra.config import Config >>> os.environ["CLEOPATRA_CACHE_DIR"] = "/ignored" >>> asset = Config.get_cache_dir("/data") / "ne_110m_coastline.geojson.gz" >>> asset.as_posix() '/data/ne_110m_coastline.geojson.gz' >>> del os.environ["CLEOPATRA_CACHE_DIR"] ``` See Also: cleopatra.basemap.reference: Downloads basemap assets into this directory (its private `_cache_dir` resolves the location through this method and creates the directory on first use). """candidate=os.fspath(path)ifpathisnotNoneelseNoneifcandidateisNoneornotcandidate.strip():candidate=os.environ.get("CLEOPATRA_CACHE_DIR")ifcandidateandcandidate.strip():returnPath(candidate).expanduser()returnPath.home()/".cleopatra"/"naturalearth"
Switch the active matplotlib backend (opt-in helper).
cleopatra does not call this automatically. It is provided for
users who want a one-liner to pick a backend. Switching the
backend closes every currently-open figure — that is
matplotlib's behaviour, not cleopatra's — so call this before you
start plotting.
Parameters:
Name
Type
Description
Default
backend
str | None
Backend name to switch to (e.g. "Agg", "TkAgg",
"Qt5Agg"). If None, an environment-appropriate default
is chosen: %matplotlib inline inside a Jupyter notebook
(or %matplotlib notebook when interactive is True),
otherwise "Agg".
None
interactive
bool
When backend is None and running inside a
Jupyter notebook, use the interactive notebook backend
instead of inline. Ignored otherwise. Default False.
@staticmethoddefset_matplotlib_backend(backend:str|None=None,interactive:bool=False)->str:"""Switch the active matplotlib backend (opt-in helper). cleopatra does not call this automatically. It is provided for users who want a one-liner to pick a backend. Switching the backend **closes every currently-open figure** — that is matplotlib's behaviour, not cleopatra's — so call this before you start plotting. Args: backend: Backend name to switch to (e.g. `"Agg"`, `"TkAgg"`, `"Qt5Agg"`). If `None`, an environment-appropriate default is chosen: `%matplotlib inline` inside a Jupyter notebook (or `%matplotlib notebook` when `interactive` is `True`), otherwise `"Agg"`. interactive: When `backend` is `None` and running inside a Jupyter notebook, use the interactive notebook backend instead of inline. Ignored otherwise. Default `False`. Returns: str: The name of the backend that is now active. """importmatplotlib.pyplotaspltifbackend:plt.switch_backend(backend)logger.info("Matplotlib backend set to %s",backend)elifis_notebook():fromIPythonimportget_ipythonmagic="notebook"ifinteractiveelse"inline"get_ipython().run_line_magic("matplotlib",magic)logger.info("Matplotlib set to %%matplotlib %s for Jupyter",magic)else:plt.switch_backend("Agg")logger.info("Matplotlib backend set to Agg (non-interactive)")returnmatplotlib.get_backend()
defis_notebook()->bool:"""Return True if the code is running in a Jupyter notebook / qtconsole."""try:fromIPythonimportget_ipythonexceptModuleNotFoundError:returnFalse# IPython is not installed.# Only Jupyter / qtconsole report "ZMQInteractiveShell"; a terminal IPython# ("TerminalInteractiveShell") or any other environment is not a notebook.shell=get_ipython().__class__.__name__returnshell=="ZMQInteractiveShell"