API Reference#

Core Package#

tollan Package#

Top-level package for tollan.

tollan.cli Package#

Console script for tollan.

Configuration System#

tollan.config Package#

Configuration system using ConfigSourceList and RuntimeContext.

This module provides a modern configuration system with two main components.

Architecture:

RuntimeContext (entry point) - Manages config lifecycle and context
    ↓ owns
ConfigSourceList (config loader) - Loads and merges config from multiple sources
    ↓ consumed by
ConfigHandler (domain adapter) - Validates and caches domain-specific config

Sources Supported#

  • YAML files (including conditional loading with enable_if)

  • Dictionary sources

  • Environment files (.env)

  • Nested config source lists

Basic Example:
>>> from pathlib import Path
>>> from tollan.config import RuntimeContext
>>> rc = RuntimeContext(
...     config_sources=[
...         {"format": "dict", "source": {"app": "test"}, "order": 0},
...         {
...             "format": "dict",
...             "source": {"debug": True},
...             "order": 1,
...             "enable_if": "env == 'production'",
...         }
...     ]
... )
>>> config_dict = rc.config_dict  # Merged config dict (cached property)
>>> config = rc.config  # Validated RuntimeConfig model (cached property)
>>> runtime_info = rc.runtime_info  # Auto-detected runtime info
CLI Example (with factory method):
>>> from pathlib import Path
>>> from tollan.config import RuntimeContext
>>> # CLI parsing example (doesn't require files)
>>> rc = RuntimeContext.from_cli(cli_args=["--debug", "true", "--port", "8080"])
>>> rc.config_dict['debug']
True
Context Override Example:
>>> with rc.set_context({"env": "production"}):
...     prod_config = rc.config_dict
Domain-Specific Example (with ConfigHandler):
>>> # See ConfigHandler documentation for complete example
...

Classes#

ConfigHandler(runtime_context)

Base class for domain-specific configuration handlers.

FrozenBaseModel

Base model class with immutability and YAML support.

RuntimeConfig

Base configuration model with runtime info.

RuntimeContext([config_sources])

Entry point for runtime-aware configuration management.

RuntimeInfo

Runtime environment information.

SubConfigKeyTransformer()

Mixin for handlers that extract a subkey from runtime config.

Class Inheritance Diagram#

Inheritance diagram of tollan.config.handler.ConfigHandler, tollan.config.base.FrozenBaseModel, tollan.config.runtime_context.RuntimeConfig, tollan.config.runtime_context.RuntimeContext, tollan.config.runtime_info.RuntimeInfo, tollan.config.handler.SubConfigKeyTransformer

tollan.config.sources Package#

Configuration sources for loading config from various formats.

Functions#

resolve_config_sources(arg[, order_max, ...])

Create a ConfigSourceList from various input formats.

Classes#

ConfigSourceList

A list of configuration sources with conditional loading.

DictConfigSource

Configuration source from dictionary.

EnvFileConfigSource

Configuration source from .env file.

ListConfigSource

Configuration source from nested list of sources.

YamlConfigSource

Configuration source from YAML file.

Class Inheritance Diagram#

Inheritance diagram of tollan.config.sources.ConfigSourceList, tollan.config.sources.dict_.DictConfigSource, tollan.config.sources.envfile.EnvFileConfigSource, tollan.config.sources.list_.ListConfigSource, tollan.config.sources.yaml.YamlConfigSource

tollan.config.types Package#

Custom pydantic types for astronomy data validation.

This module provides custom Pydantic types for validating astronomy-specific data structures using astropy, including:

  • Time fields with format constraints

  • Quantity fields with physical type constraints

  • SkyCoord fields for celestial coordinates

  • Enhanced Path types with resolution and existence validation

Functions#

quantity_field([physical_types_allowed])

Create a pydantic field type for validating astropy Quantity.

time_field([formats_allowed])

Create a pydantic field type for validating astropy Time.

Classes#

FieldDefaults()

Descriptor for accessing model field defaults.

GenerateJsonSchema([by_alias, ref_template, ...])

Custom JSON schema generator with type-specific serializers.

PathValidator([path_type, exists, resolve])

Validator for Path types with rootpath context support.

Class Inheritance Diagram#

Inheritance diagram of tollan.config.types.pydantic.FieldDefaults, tollan.config.types.pydantic.GenerateJsonSchema, tollan.config.types.path.PathValidator

Pipeline#

tollan.pipeline Package#

Pipeline utils.

Classes#

ContextHandlerMixinBase()

Base class for managing context objects in data containers.

DictContextHandlerMixin()

A helper class to access context stored in dict.

MetadataContextHandlerMixin()

A helper class to access context stored in metadata dict.

Class Inheritance Diagram#

Inheritance diagram of tollan.pipeline.context_handler.ContextHandlerMixinBase, tollan.pipeline.context_handler.DictContextHandlerMixin, tollan.pipeline.context_handler.MetadataContextHandlerMixin

Plotting#

tollan.plot.mpl Module#

Matplotlib utility functions.

Functions#

move_axes(ax, ax_new, *[, remove])

Move an Axes object from a figure to a new one.

tollan.plot.plotly Module#

Plotly utilities for multi-panel figures and Dash applications.

Key features: - SubplotGrid: Stateful builder for complex multi-panel layouts with rowspan/colspan - adjust_subplot_colorbars: Fix colorbar positioning in subplots - ColorPalette: Color scaling and cycling for consistent plot styling - show_in_dash: Quick interactive data visualization in Dash with tabs

Functions#

adjust_subplot_colorbars(fig[, size])

Adjust colorbar positions to align with subplot axes.

make_empty_figure([place_holder_text])

Create an empty figure with optional placeholder text.

make_range(v[, pad, pad_frac])

Calculate data range with padding.

make_subplot_layout(fig, layout, row, col)

Create layout dict with correct axis references for a specific subplot.

make_subplots(n_rows, n_cols[, fig_layout])

Create a multi-panel figure with sensible defaults.

show_in_dash(data_items[, title_text, host, ...])

Display data items in an interactive Dash application.

update_subplot_layout(fig, fig_layout[, ...])

Update layout for all subplots or specific subplot.

Classes#

ColorPalette([name])

A class to manage colors from a named palette.

ShowInDash(data_items, ~typing.Any]], ...)

Dash layout component for displaying data items in tabs.

SubplotGrid(subplots, fig_layout)

A helper class to build multi panel figure.

Class Inheritance Diagram#

Inheritance diagram of tollan.plot.plotly.ColorPalette, tollan.plot.plotly.ShowInDash, tollan.plot.plotly.SubplotGrid

Utilities#

tollan.utils.cli Module#

A subpackage that provides CLI utilities.

Functions#

dict_from_cli_args(args)

Return a nested dict from CLI arguments.

split_cli_args(re_name, args)

Split the args based on regex match of the arg name.

tollan.utils.dict Module#

Dictionary and nested container utilities.

This module provides utilities for working with dictionaries and nested container structures (dicts and lists), including recursive updates, flattening/unflattening, and container manipulation.

Functions#

add_to_dict(d, key, *[, exist_ok])

Return a decorator to add decorated item to dict.

dict_from_flat_dict(dct)

Convert flat dict with dotted keys to nested dict structure.

dict_from_regex_match(pattern, string[, ...])

Return a dict from matching pattern to string.

dict_product(**kwargs)

Return the Cartesian product of dicts.

dict_to_flat_dict(dct[, key_prefix, ...])

Return dict from dict with nested dicts.

rupdate(d, u, *[, copy_subdict])

Update dict recursively.

tollan.utils.file Module#

Utility functions for file operations.

Functions#

ensure_abspath(p)

Return the full expanded absolute path.

ensure_path_parent_exists(path)

Ensure parent path of path exists.

ensure_readable_fileobj(arg, *args, **kwargs)

Return a readable object.

get_or_create_dir(dirpath[, on_exist, ...])

Ensure dirpath exist.

resolve_symlink(p[, n_iter_max, match_parent])

Resolve symlink chain to target path.

touch_file(out_file)

Touch file, the same as the shell command touch.

tollan.utils.fileloc Module#

File location handling utilities.

Functions#

fileloc(loc[, remote_parent_path, ...])

Return a validated FileLoc object.

Classes#

FileLoc

A model to hold file location info.

FileLocData([url, path, netloc, ...])

A helper model for storing file loc data.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.fileloc.FileLoc, tollan.utils.fileloc.FileLocData

tollan.utils.fmt Module#

Formatting utilities for YAML, masks, and bitmasks.

Includes pretty-printing for YAML, numpy masks, and Flag-based bitmasks.

Functions#

bitmask_stats(bm_cls, bitmask)

Compute statistics for each flag in a bitmask.

pformat_bitmask(bm_cls, bitmask)

Pretty-format bitmask statistics as a summary table.

pformat_fancy_index(arg)

Pretty-format a numpy fancy index, slice, or mask.

pformat_mask(mask)

Pretty-format a boolean mask as 'selected/total (percentage)'.

pformat_yaml(obj)

Pretty-format an object as a YAML string.

Classes#

BitmaskStats(bm_cls, bitmask)

Compute and format statistics for bitmask flags.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.fmt.BitmaskStats

tollan.utils.log Module#

General logging utilities.

Features: - Global loguru logger instance (logger) - Decorators/context managers for logging entry/exit (logit) and timing (timeit) - Logger reset utility (reset_logger)

Examples

>>> from tollan.utils.log import logger, logit, timeit
>>> @logit(logger.info, "Running task")
... def task():
...     pass
>>> @timeit
... def timed_task():
...     pass

Functions#

reset_logger([sink, verbose, level])

Reset the global logger to default configuration.

Classes#

logit(log_func, msg[, base_depth])

Decorator/context manager to log entry and exit of a function or code block.

timeit()

Decorator/context manager to log execution time of a function or code block.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.log.logit, tollan.utils.log.timeit

tollan.utils.np Module#

NumPy and astropy.units utility functions.

Unified helpers for NumPy arrays and astropy quantities. Includes unit handling, reshaping, and complex array creation.

Functions#

attach_unit(arr, unit)

Attach a unit to an array if unit is not None.

ensure_unit(arr, unit)

Ensure data has the given unit (returns None if arr is None).

flex_reshape(arr, shape[, trim_option])

Reshape an array, trimming elements if needed.

make_complex(real_part, imag_part)

Create a complex array from real and imaginary parts.

preserve_unit(f)

Strip unit from first argument, reattach to result.

qrange(x0, x1, step)

Like numpy.arange, but for astropy quantities (unit-aware).

strip_unit()

Remove unit from array, returning (data, unit).

tollan.utils.py Module#

Python utility classes and functions.

Functions#

getname(obj[, sep])

Return the specifier name of a Python object (opposite of getobj).

getobj(name, *args)

Return a Python object by dotted path (e.g. 'module:attr.subattr').

module_from_path(filepath[, name])

Load a Python module from a file path.

rgetattr(obj, attr, *args)

Recursively get a nested attribute (e.g. 'a.b.c').

rreload(m)

Recursively reload a module and all its submodules.

Classes#

ObjectProxy(*args, **kwargs)

Proxy object for deferred initialization.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.py.ObjectProxy

tollan.utils.sys Module#

System-related utility functions.

Functions#

get_hostname()

Return the system hostname.

get_username()

Return the current user's username.

pty_run(cmd)

Run a command in a pseudo-terminal (pty).

tollan.utils.table Module#

Table validation utilities for astropy and pandas tables.

Provides unified helpers for working with both astropy Table/QTable and pandas DataFrame objects.

Examples

>>> from astropy.table import Table
>>> from tollan.utils.table import TableValidator
>>> tbl = Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
>>> TableValidator().has_all_cols(tbl, ['a', 'b'])
True

Classes#

TableValidator()

Validator for astropy and pandas tables.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.table.TableValidator

tollan.utils.typer Module#

Typer CLI utility functions.

This module extends Typer’s CLI functionality with custom options and utilities. The main feature is MultiOption, which enables variable-length option arguments in Typer commands, with automatic type conversion via Typer’s built-in system.

Functions#

MultiOption([default])

Create a multi-argument option for Typer commands.

create_cli([version])

Return a new CLI app with reasonable defaults.

Classes#

MultiOptionInfo(option_info)

Extended OptionInfo for multi-argument options.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.typer.MultiOptionInfo

tollan.utils.typing Module#

Type introspection utilities for working with generic types.

Functions#

ensure_cls_attr_from_type_args(cls, attr_name)

Ensure a class attribute is set from typing arguments.

get_typing_args(cls[, max_depth, bound, ...])

Extract typing arguments from a class's generic base classes.

tollan.utils.yaml Module#

YAML utilities for tollan.

This module provides custom YAML dumpers and loaders with support for astronomy-specific types (Time, Quantity, SkyCoord).

Examples

>>> from tollan.utils.yaml import yaml_dump
>>> from astropy.time import Time
>>> from astropy import units as u
>>> data = {'time': Time('2020-01-01'), 'length': 5.0 * u.m}
>>> yaml_str = yaml_dump(data)
>>> print(yaml_str)
length: 5.0 m
time: '2020-01-01T00:00:00.000'

Functions#

add_numpy_scalar_representers(dumper_cls)

Add representers for numpy types to the given dumper class.

yaml_dump()

Serialize data as YAML and write to a file, stream, or return as string.

yaml_load(source)

Load YAML data from a file, stream, or string.

yaml_loads(stream)

Load YAML data from a string or stream.

Classes#

YamlDumper(stream[, default_style, ...])

YAML dumper with support for astronomy types and common scientific objects.

Class Inheritance Diagram#

Inheritance diagram of tollan.utils.yaml.YamlDumper