Config

Configure application.

class Config(settings: AppSettings, args: bool = True, config_file: str = '/home/runner/.config/visiomatic/visiomatic.conf')[source]

Bases: object

Manage application settings in groups.

Settings are stored as Pydantic fields.

grouped_dict() dict[source]

Return a dictionary of all settings, organized in groups.

Returns:

gdict (dict) -- Dictionary of settings.

flat_dict() dict[source]

Return a flattened dictionary of all settings.

Returns:

fdict (dict) -- Dictionary of settings.

schema() dict[source]

Return a schema of the settings as a dictionary.

Returns:

schema (dict) -- Schema of the settings, as a dictionary.

schema_json(indent=2) str[source]

Return a schema of the settings as a JSON string.

Parameters:

indent (int) -- Number of indentation spaces.

Returns:

schema (str) -- JSON schema of the settings.

parse_args() dict[source]

Return a dictionary of all settings, with values updated from the command line.

Extra settings are ignored.

Returns:

gdict (dict) -- Dictionary of all settings, organized in groups.

parse_config(filename: str) dict[source]

Return a dictionary of all settings, with values updated from a configuration file in INI format.

Extra settings are ignored.

Parameters:

filename (str | Path) -- Configuration filename.

Returns:

gdict (dict) -- Dictionary of all settings, organized in groups.

save_config(filename) None[source]

Save all settings as a configuration file in INI format.

Extra settings are ignored.

Parameters:

filename (str | Path) -- Configuration filename.

update_from_dict(settings_dict) None[source]

Update internal settings based on a dictionary (in groups)

Parameters:

settings_dict (dict) -- Input dictionary.

Group and define Pydantic-compatible fields.

SField(short: str | None = None, **kwargs) Any[source]

Return Pydantic field with augmented JSON schema including a command-line "shortcut" keyword.

Examples

>>> from pydantic_settings import BaseSettings
>>> class Settings(BaseSettings):
...     parameter: float = SField(
...         short='p',
...         description="an arbitrary parameter",
...         default=10.,
...     )
>>> s = Settings(parameter=3.)
>>> s.model_json_schema()
{'additionalProperties': False, 'properties': {'parameter': {'default': 10.0,
'description': 'an arbitrary parameter', 'short': 'p', 'title': 'Parameter',
'type': 'number'}}, 'title': 'Settings', 'type': 'object'}
Parameters:
  • short (str, optional) -- Shortcut for keyword

  • **kwargs -- Additional Field arguments.

Returns:

Pydantic Field with augmented JSON schema.

Provide Pydantic-compatible annotations and fields for validating and serializing AstroPy unit-aware "quantities"

class QuantityAnnotation(unit: str, *, description: str = '', min_shape: Tuple[int, ...] | None = None, max_shape: Tuple[int, ...] | None = None, ge: Quantity | str | None = None, gt: Quantity | str | None = None, le: Quantity | str | None = None, lt: Quantity | str | None = None, ser_mode: Literal['str', 'dict'] | None = None, strict: bool = True)[source]

Bases: object

Pydantic compatible annotation for validating and serializing AstroPy Quantity fields. Loosely adapted from pint-quantity by Tyler Hughes <tylerxh111+git@proton.me>

Examples

>>> from typing import Annotated
>>> from astropy import units as u
>>> from pydantic import BaseModel
>>> from .quantity import QuantityAnnotation
>>> class Coordinates(BaseModel):
...     latitude: Annotated[
...         u.Quantity, QuantityAnnotation("deg", ge=-90.*u.deg, le=90.*u.deg)
...     ]
...     longitude: Annotated[u.Quantity, QuantityAnnotation("deg")]
...     altitude: Annotated[u.Quantity, QuantityAnnotation("km")]
>>> # The following instantiation validates
>>> coord = Coordinates(
...     latitude="39.905705 deg",
...     longitude="-75.166519 deg",
...     altitude="12 m"
... )
>>> coord
Coordinates(latitude=<Quantity 39.905705 deg>,
longitude=<Quantity -75.166519 deg>, altitude=<Quantity 0.012 km>)
>>> f"{coord!r}"
'Coordinates(latitude=<Quantity 39.905705 deg>,
longitude=<Quantity -75.166519 deg>, altitude=<Quantity 0.012 km>)'
>>> coord.model_dump()
{'latitude': <Quantity 39.905705 deg>, 'longitude': <Quantity -75.166519 deg>,
'altitude': <Quantity 0.012 km>}
>>> coord.model_dump(mode="json")
{'latitude': '39.905705 deg', 'longitude': '-75.166519 deg',
'altitude': '0.012 km'}
>>> coord.model_dump_json()
'{"latitude":"39.905705 deg","longitude":"-75.166519 deg","altitude":"0.012 km"}'
>>> # The following instantiation does not validate
>>> coord = Coordinates(
...     latitude="99.905705 deg",
...     longitude="-75.166519 deg",
...     altitude="12 m"
... )
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for Coordinates
latitude
Value error, greater than 90.0 deg
[type=value_error, input_value='99.905705 deg', input_type=str]
For further information visit https://errors.pydantic.dev/2.7/v/value_error
Parameters:
  • unit (str) -- The unit type of the Pydantic field (e.g., "m", or "deg"). All input units must be convertible to this unit.

  • min_shape (tuple[int], optional) -- Minimum number of vector components on each axis.

  • max_shape (tuple[int], optional) -- Maximum number of vector components on each axis.

  • ge (Quantity or str, optional) -- Lower limit (inclusive).

  • gt (Quantity or str, optional) -- Lower limit (strict).

  • le (Quantity or str, optional) -- Lower limit (inclusive).

  • lt (Quantity or str, optional) -- Lower limit (strict).

  • ser_mode (Literal["str", "dict"], optional) -- The mode for serializing the field; either "str" or "dict". By default, in Pydantic's "python" serialization mode, fields are serialized to a Quantity; in Pydantic's "json" serialization mode, fields are serialized to a str.

  • strict (bool, optional) -- Forces users to specify units; on by default. If disabled, a value without units - provided by the user - will be treated as the base units of the QuantityUnit.

validate(v: dict | str | Number | Quantity, info: ValidationInfo | None = None) Quantity[source]

Validate Quantity.

Parameters:
  • v (dict | str | numbers.Number ~astropy.units.Quantity) -- Quantity that should be validated.

  • info (ValidationInfo, optional) -- The validation info provided by the Pydantic schema.

Returns:

v (~astropy.units.Quantity) -- Validated Quantity with the correct units.

Raises:
  • ValueError -- exception: An error occurred validating the specified value. It is raised if any of the following occur: - A dict is received and the keys "value" and "units" do not exist. - There are no units provided. - Provided units cannot be converted to base units. - An unknown unit was provided. - An unknown type for value was provided.

  • TypeError -- exception: An error occurred from unit registry or unit registry context. It is not propagated as a pydantic.ValidationError because it does not stem from a user error.

serialize(v: Quantity, info: SerializationInfo | None = None, *, to_json: bool = False) dict | str | Quantity[source]

Serialize Quantity.

Parameters:
  • v (Quantity) -- Quantity that should be serialized.

  • info (pydantic.core_schema.SerializationInfo, optional) -- Serialization info provided by the Pydantic schema.

  • to_json (bool, optional) -- Whether or not to serialize to a json convertible object. Useful if using QuantityUnit as a utility outside of Pydantic models.

Returns:

quantity (str) -- The serialized Quantity.

AnnotatedQuantity(default: Quantity | str, short: str | None = None, description: str = '', min_shape: Tuple[int, ...] | None = None, max_shape: Tuple[int, ...] | None = None, ge: Quantity | str | None = None, gt: Quantity | str | None = None, le: Quantity | str | None = None, lt: Quantity | str | None = None) Any[source]

Pydantic pseudo-field for validating and serializing AstroPy Quantities.

Examples

>>> from pydantic_settings import BaseSettings
>>> from .quantity import AnnotatedQuantity
>>> class Settings(BaseSettings):
...     size: AnnotatedQuantity(
...         short='S',
...         description="an arbitrary length",
...         default=10. * u.m,
...         ge=1. * u.micron,
...         lt=1. * u.km
...     )
>>> # The following instantiation validates
>>> s = Settings(size="3. cm")
>>> s
Settings(size=<Quantity 0.03 m>)
>>> f"{s!r}"
'Settings(size=<Quantity 0.03 m>)'
>>> s.model_dump()
{'size': <Quantity 0.03 m>}
>>> s.model_dump(mode="json")
{'size': '0.03 m'}
>>> s.model_json_schema()
{'additionalProperties': False, 'properties': {'size': {'default':
'10.0 m', 'description': 'an arbitrary length', 'exclusiveMaximum':
'1.0 km', 'minimum': '1.0 micron', 'physType': 'length', 'short': 'S',
'title': 'Size', 'type': 'string'}}, 'title': 'Settings', 'type':
'object'}
>>> # The following instantiation does not validate
>>> s = Settings(size="4 deg")
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
size
Value error, 'deg' (angle) and 'm' (length) are not convertible
[type=value_error, input_value='4 deg', input_type=str]
For further information visit https://errors.pydantic.dev/2.8/v/value_error
Parameters:
  • default (Quantity or str) -- Default value.

  • short (str, optional) -- shortcut for keyword.

  • description (str, optional) -- Description string.

  • min_shape (tuple[int], optional) -- Minimum number of vector components on each axis.

  • max_shape (tuple[int], optional) -- Maximum number of vector components on each axis.

  • ge (Quantity or str, optional) -- Lower limit (inclusive).

  • gt (Quantity or str, optional) -- Lower limit (strict).

  • le (Quantity or str, optional) -- Lower limit (inclusive).

  • lt (Quantity or str, optional) -- Lower limit (strict).

str_to_quantity_array(s: str) Quantity | None[source]

Convert string to Astropy "units" Quantity array

Notes

Currently limited to "well-formed", 1D arrays.

Examples

>>> from .quantity import str_to_quantity_array
>>> str_to_quantity_array("[3.14, 1e+06] m")
<Quantity [3.14e+00, 1.00e+06] m>
Parameters:

s (str) -- Input string.

Returns:

v (~astropy.units.Quantity) -- Astropy units Quantity object.

Configure application.

override(key: str, value: Any) Any[source]

Convenience function that returns the input value unless it is None, in which case the settings value from key is returned.

Examples

>>> from . import override, settings
>>> settings['port'] = 8009
>>> print(f"{override('port', 8080)}")
8080
>>> print(f"{override('port', None)}")
8009
Parameters:
  • key (str) -- Key to settings value.

  • value (Any) -- Input value.

Returns:

value (Any) -- Input value or settings value.