Shared Utilities¶
This module contains shared utilities and common functionality used across the mango library.
Constants¶
ARCGIS CONSTANTS
Decorators¶
- mango.shared.decorators.validate_args(**schemas)¶
Decorator to validate function arguments against JSON schemas.
Validates keyword arguments against provided JSON schemas before executing the decorated function. Schemas can be provided as dictionaries or file paths to JSON schema files.
- Parameters:
schemas (dict) – Dictionary mapping argument names to their validation schemas
- Returns:
Decorator function
- Return type:
callable
- Raises:
ValidationError – If any argument fails validation
ValueError – If schema format is invalid
- Example:
>>> schema = { ... "type": "object", ... "properties": { ... "name": {"type": "string"}, ... "age": {"type": "integer", "minimum": 0} ... }, ... "required": ["name"] ... } >>> @validate_args(user=schema) ... def create_user(user): ... return f"Created user: {user['name']}" >>> create_user(user={"name": "John", "age": 30}) 'Created user: John'
- mango.shared.decorators.pydantic_validation(*validator, on_validation_error: Literal['raise', 'warn', 'ignore'] = 'raise', strict_validation: bool = True, **named_validators)¶
Decorator to validate function arguments using Pydantic models.
Provides comprehensive argument validation using Pydantic models with flexible error handling options. Supports both global validation (all arguments) and selective validation (specific arguments only).
- Parameters:
validator (BaseModel, optional) – Pydantic model to validate all arguments against
on_validation_error (Literal["raise", "warn", "ignore"]) – Action to take on validation failure
strict_validation (bool) – Whether to use strict validation (no type coercion)
named_validators (dict[str, BaseModel]) – Dictionary mapping argument names to Pydantic models
- Returns:
Decorator function
- Return type:
callable
- Raises:
ValidationError – If validation fails and on_validation_error=”raise”
ValueError – If function has positional arguments or invalid error handling option
- Example:
>>> from pydantic import BaseModel >>> >>> class UserModel(BaseModel): ... name: str ... age: int ... email: str >>> >>> @pydantic_validation(UserModel) ... def create_user(*, name: str, age: int, email: str): ... return f"User {name} created" >>> >>> create_user(name="John", age=30, email="john@example.com") 'User John created' >>> >>> # With selective validation >>> @pydantic_validation(user_data=UserModel) ... def process_user(user_data: dict, action: str): ... return f"Processing {user_data['name']} with action {action}"
Exceptions¶
- exception mango.shared.exceptions.InvalidCredentials¶
- add_note()¶
Exception.add_note(note) – add a note to the exception
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception mango.shared.exceptions.ValidationError¶
- add_note()¶
Exception.add_note(note) – add a note to the exception
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception mango.shared.exceptions.JobError¶
- add_note()¶
Exception.add_note(note) – add a note to the exception
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
Requirement Check¶
- mango.shared.requirement_check.check_dependencies(dependencies_name: str, pyproject_path: str = None)¶
Verify if optional dependencies have been installed for better ImportError handling.
Checks whether all dependencies specified in a named optional dependency group in pyproject.toml are currently installed. This function provides better error handling for missing optional dependencies by giving clear installation instructions.
- Parameters:
dependencies_name (str) – Name of the optional dependencies group as defined in pyproject.toml
pyproject_path (str, optional) – Path to pyproject.toml file. If None, searches in parent directory
- Returns:
True if all dependencies are satisfied, False if any are missing
- Return type:
bool
- Raises:
FileNotFoundError – If pyproject.toml file cannot be found
KeyError – If the specified dependency group name is not found in pyproject.toml
- Example:
>>> # Check if visualization dependencies are installed >>> check_dependencies("visualization") True >>> >>> # Check with custom pyproject.toml path >>> check_dependencies("ml", "/path/to/custom/pyproject.toml") False
Spatial Functions¶
- class mango.shared.spatial.HaversineArgs(*args: Any, **kwargs: Any)¶
Pydantic model for validating Haversine distance calculation arguments.
Validates that the provided coordinates are within valid latitude and longitude ranges for geographic calculations.
- Parameters:
point1 (Tuple[float, float]) – First geographic point as (latitude, longitude) tuple
point2 (Tuple[float, float]) – Second geographic point as (latitude, longitude) tuple
- Raises:
ValidationError – If coordinates are outside valid ranges
- mango.shared.spatial.haversine(point1, point2) → float¶
Calculate the great circle distance between two points on Earth.
Computes the shortest distance between two points on the surface of a sphere (Earth) using the Haversine formula. The result is returned in kilometers. This implementation assumes Earth is a perfect sphere.
For higher precision calculations, consider using geopy which implements geodesic calculations that account for Earth’s ellipsoidal shape.
- Parameters:
point1 (Tuple[float, float]) – First geographic point as (latitude, longitude) tuple in decimal degrees
point2 (Tuple[float, float]) – Second geographic point as (latitude, longitude) tuple in decimal degrees
- Returns:
Distance between the two points in kilometers
- Return type:
float
- Raises:
ValidationError – If coordinates are outside valid ranges (-90 to 90 for latitude, -180 to 180 for longitude)
- Example:
>>> # Distance between Madrid and Barcelona >>> madrid = (40.4168, -3.7038) >>> barcelona = (41.3851, 2.1734) >>> distance = haversine(madrid, barcelona) >>> print(f"Distance: {distance:.2f} km") Distance: 504.47 km >>> >>> # Distance between New York and London >>> nyc = (40.7128, -74.0060) >>> london = (51.5074, -0.1278) >>> distance = haversine(nyc, london) >>> print(f"Distance: {distance:.2f} km") Distance: 5570.25 km