units
units
Project-wide control over whether values carry astropy units.
planetarypy already speaks astropy units in places — :mod:planetarypy.constants returns :class:~astropy.units.Quantity subclasses, and the SPICE layer wraps selected results — but there was no way to say “units everywhere” or “plain floats, please” once and have it hold. This module is that switch.
>>> from planetarypy import units
>>> units.set_units(False) # plain floats for this session
>>> with units.use_units(True): ... # ...except inside this block
Units are on by default, matching what constants already does. Turning them off is for code that feeds values straight into libraries which choke on Quantity — numba kernels, some plotting paths, JSON serialisation.
Design mirrors :mod:planetarypy.crs’s target-CRS switch deliberately: same setter/getter/context-manager trio, same ContextVar backing, so the two session settings behave identically and nest the same way.
Functions
| Name | Description |
|---|---|
| attach_units | Record {column: unit} on a DataFrame’s .attrs. Returns the frame. |
| get_units | Whether values should currently carry units. |
| maybe_quantity | value * unit when units are enabled, otherwise value untouched. |
| set_units | Turn astropy units on or off for the session. Returns the previous value. |
| units_of | The unit map a DataFrame carries in .attrs, or {}. |
| use_units | Context-manager form of :func:set_units. |
attach_units
units.attach_units(frame, unit_map)Record {column: unit} on a DataFrame’s .attrs. Returns the frame.
get_units
units.get_units()Whether values should currently carry units.
maybe_quantity
units.maybe_quantity(value, unit)value * unit when units are enabled, otherwise value untouched.
The single place the toggle is consulted, so callers never branch on it themselves and every module honours the setting identically.
set_units
units.set_units(enabled)Turn astropy units on or off for the session. Returns the previous value.
units_of
units.units_of(obj)The unit map a DataFrame carries in .attrs, or {}.
Units are recorded on the frame regardless of the toggle — knowing that diameter is km costs nothing and stays true — while the toggle governs only whether individual values are wrapped.
use_units
units.use_units(enabled=True)Context-manager form of :func:set_units.
with use_units(False): … plain = nomenclature.find(“mars”, “Jezero”).diameter # float # previous setting restored here, even if the block raised
Nests, and restores on exception.