fsspeckit.common API Reference¶
common
¶
Cross-cutting utilities for fsspeckit.
This package contains dependency-free utilities shared across all components: - Datetime parsing and manipulation utilities - Logging configuration and helpers - General purpose utility functions (parallelism, filesystem sync) - Partition column helpers - Path and security validation
Schema, polars, and type-conversion utilities live in fsspeckit.datasets
because they require optional dependencies (pyarrow, numpy, polars).
Attributes¶
fsspeckit.common.VALID_COMPRESSION_CODECS
module-attribute
¶
VALID_COMPRESSION_CODECS = frozenset(
{
"snappy",
"gzip",
"lz4",
"zstd",
"brotli",
"uncompressed",
"none",
}
)
Functions¶
fsspeckit.common.get_timestamp_column
¶
Get timestamp column names from a DataFrame or PyArrow Table.
Automatically detects and normalizes different DataFrame types to work with pandas DataFrames, Polars DataFrames/LazyFrames, and PyArrow Tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
Any
|
A Polars DataFrame/LazyFrame, PyArrow Table, or pandas DataFrame. The function automatically converts pandas DataFrames and PyArrow Tables to Polars LazyFrames for consistent timestamp detection. |
required |
Returns:
| Type | Description |
|---|---|
str | list[str]
|
List of strings containing timestamp column names. Returns an empty list |
str | list[str]
|
if no timestamp columns are found. |
Examples:
Source code in src/fsspeckit/common/datetime.py
fsspeckit.common.get_timedelta_str
¶
Convert timedelta strings between different formats.
Converts timedelta strings between Polars and DuckDB formats, with graceful fallback for unknown units. Never raises errors for unknown units - instead returns a reasonable string representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timedelta_string
|
str
|
Input timedelta string (e.g., "1h", "2d", "5invalid"). |
required |
to
|
str
|
Target format - "polars" or "duckdb". Defaults to "polars". |
'polars'
|
Returns:
| Type | Description |
|---|---|
str
|
String in the target format. For unknown units, returns "value unit" |
str
|
format without raising errors. |
Examples:
Source code in src/fsspeckit/common/datetime.py
fsspeckit.common.timestamp_from_string
cached
¶
timestamp_from_string(
timestamp_str: str,
tz: str | None = None,
naive: bool = False,
) -> datetime | date | time
Converts a timestamp string (ISO 8601 format) into a datetime, date, or time object using only standard Python libraries.
Handles strings with or without timezone information (e.g., '2023-01-01T10:00:00+02:00', '2023-01-01', '10:00:00'). Supports timezone offsets like '+HH:MM' or '+HHMM'. For named timezones (e.g., 'Europe/Paris'), requires Python 3.9+ and the 'tzdata' package to be installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp_str
|
str
|
The string representation of the timestamp (ISO 8601 format). |
required |
tz
|
str
|
Target timezone identifier (e.g., 'UTC', '+02:00', 'Europe/Paris'). If provided, the output datetime/time will be localized or converted to this timezone. Defaults to None. |
None
|
naive
|
bool
|
If True, return a naive datetime/time (no timezone info),
even if the input string or |
False
|
Returns:
| Type | Description |
|---|---|
datetime | date | time
|
Union[dt.datetime, dt.date, dt.time]: The parsed datetime, date, or time object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the timestamp string format is invalid or the timezone is invalid/unsupported. |
Source code in src/fsspeckit/common/datetime.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
fsspeckit.common.get_logger
¶
Get a logger instance for the given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name, typically the module name. |
'fsspeckit'
|
Returns:
| Type | Description |
|---|---|
logger
|
Configured logger instance. |
Source code in src/fsspeckit/common/logging/config.py
fsspeckit.common.setup_logging
¶
setup_logging(
level: str | None = None,
disable: bool = False,
format_string: str | None = None,
) -> None
Configure the Loguru logger for fsspeckit.
Removes the default handler and adds a new one targeting stderr with customizable level and format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str | None
|
Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL). If None, uses fsspeckit_LOG_LEVEL environment variable or defaults to "INFO". |
None
|
disable
|
bool
|
Whether to disable logging for fsspeckit package. |
False
|
format_string
|
str | None
|
Custom format string for log messages. If None, uses a default comprehensive format. |
None
|
Example
Source code in src/fsspeckit/common/logging/config.py
fsspeckit.common.get_partitions_from_path
¶
Extract dataset partitions from a file path.
Parses file paths to extract partition information based on different partitioning schemes. This is the canonical implementation used across all fsspeckit backends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path potentially containing partition information. |
required |
partitioning
|
str | list[str] | None
|
Partitioning scheme: - "hive": Hive-style partitioning (key=value) - str: Single partition column name - list[str]: Multiple partition column names - None: Return empty list |
None
|
Returns:
| Type | Description |
|---|---|
list[tuple]
|
List of tuples containing (column, value) pairs. |
Examples:
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.normalize_partition_value
¶
Normalize a partition value for consistent comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
Raw partition value from path. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Normalized partition value. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.validate_partition_columns
¶
validate_partition_columns(
partitions: list[tuple[str, str]],
expected_columns: list[str] | None = None,
) -> bool
Validate partition columns against expected schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
partitions
|
list[tuple[str, str]]
|
List of (column, value) tuples. |
required |
expected_columns
|
list[str] | None
|
Optional list of expected column names. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if partitions are valid, False otherwise. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.build_partition_path
¶
build_partition_path(
base_path: str,
partitions: list[tuple[str, str]],
partitioning: str = "hive",
) -> str
Build a file path with partition directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
str
|
Base directory path. |
required |
partitions
|
list[tuple[str, str]]
|
List of (column, value) tuples. |
required |
partitioning
|
str
|
Partitioning scheme ("hive" or "directory"). |
'hive'
|
Returns:
| Type | Description |
|---|---|
str
|
Path string with partition directories. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.extract_partition_filters
¶
extract_partition_filters(
paths: list[str],
partitioning: str | list[str] | None = None,
) -> dict[str, set[str]]
Extract unique partition values from a list of paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths. |
required |
partitioning
|
str | list[str] | None
|
Partitioning scheme. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, set[str]]
|
Dictionary mapping column names to sets of unique values. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.filter_paths_by_partitions
¶
filter_paths_by_partitions(
paths: list[str],
partition_filters: dict[str, str | list[str]],
partitioning: str | list[str] | None = None,
) -> list[str]
Filter paths based on partition values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths to filter. |
required |
partition_filters
|
dict[str, str | list[str]]
|
Dictionary mapping column names to filter values. |
required |
partitioning
|
str | list[str] | None
|
Partitioning scheme. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Filtered list of paths. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.infer_partitioning_scheme
¶
Infer the partitioning scheme from a sample of paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths to analyze. |
required |
max_samples
|
int
|
Maximum number of paths to sample. |
100
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with inferred scheme information. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.get_partition_columns_from_paths
¶
get_partition_columns_from_paths(
paths: list[str],
partitioning: str | list[str] | None = None,
) -> list[str]
Get all unique partition column names from a list of paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of file paths. |
required |
partitioning
|
str | list[str] | None
|
Partitioning scheme. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of unique partition column names. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.create_partition_expression
¶
Create a partition filter expression for different backends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
partitions
|
list[tuple[str, str]]
|
List of (column, value) tuples. |
required |
backend
|
str
|
Target backend ("pyarrow", "duckdb"). |
'pyarrow'
|
Returns:
| Type | Description |
|---|---|
Any
|
Backend-specific filter expression. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.apply_partition_pruning
¶
apply_partition_pruning(
paths: list[str],
partition_filters: dict[str, Any],
partitioning: str | list[str] | None = None,
) -> list[str]
Apply partition pruning to reduce the set of files to scan.
This is an optimization that eliminates files based on partition values before any I/O operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str]
|
List of all file paths. |
required |
partition_filters
|
dict[str, Any]
|
Dictionary of partition filters to apply. |
required |
partitioning
|
str | list[str] | None
|
Partitioning scheme. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Pruned list of paths. |
Source code in src/fsspeckit/common/partitions.py
fsspeckit.common.run_parallel
¶
run_parallel(
func: Callable,
*args: Any,
n_jobs: int = -1,
backend: str = "threading",
verbose: bool = True,
**kwargs: Any,
) -> list[Any]
Runs a function for a list of parameters in parallel.
Requires: fsspeckit[datasets] extra for joblib dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function to run in parallel |
required |
*args
|
Any
|
Positional arguments. Can be single values or any non-string iterables (including generators) |
()
|
n_jobs
|
int
|
Number of joblib workers. Defaults to -1 |
-1
|
backend
|
str
|
joblib backend. Valid options are
|
'threading'
|
verbose
|
bool
|
Show progress bar. Defaults to True |
True
|
**kwargs
|
Any
|
Keyword arguments. Can be single values or any non-string iterables (including generators) |
{}
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
list[any]: Function output |
Raises:
| Type | Description |
|---|---|
ImportError
|
If joblib is not available. Install with: pip install fsspeckit[datasets] |
ValueError
|
If no iterable arguments are provided or iterables have different lengths |
Examples:
Source code in src/fsspeckit/common/parallel.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
fsspeckit.common.sync_dir
¶
sync_dir(
src_fs: AbstractFileSystem,
dst_fs: AbstractFileSystem,
src_path: str = "",
dst_path: str = "",
server_side: bool = True,
chunk_size: int = 8 * 1024 * 1024,
parallel: bool = False,
n_jobs: int = -1,
verbose: bool = True,
) -> dict[str, list[str]]
Sync two directories between different filesystems.
Compares files in the source and destination directories, copies new or updated files from source to destination, and deletes stale files from destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fs
|
AbstractFileSystem
|
Source filesystem (fsspec AbstractFileSystem) |
required |
dst_fs
|
AbstractFileSystem
|
Destination filesystem (fsspec AbstractFileSystem) |
required |
src_path
|
str
|
Path in source filesystem to sync. Default is root (''). |
''
|
dst_path
|
str
|
Path in destination filesystem to sync. Default is root (''). |
''
|
server_side
|
bool
|
Whether to use server-side copy if supported. Default is True. |
True
|
chunk_size
|
int
|
Size of chunks to read/write files (in bytes). Default is 8MB. |
8 * 1024 * 1024
|
parallel
|
bool
|
Whether to perform copy/delete operations in parallel. Default is False. |
False
|
n_jobs
|
int
|
Number of parallel jobs if parallel=True. Default is -1 (all cores). |
-1
|
verbose
|
bool
|
Whether to show progress bars. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, list[str]]
|
Summary of added and deleted files |
Source code in src/fsspeckit/common/sync.py
fsspeckit.common.sync_files
¶
sync_files(
add_files: list[str],
delete_files: list[str],
src_fs: AbstractFileSystem,
dst_fs: AbstractFileSystem,
src_path: str = "",
dst_path: str = "",
server_side: bool = False,
chunk_size: int = 8 * 1024 * 1024,
parallel: bool = False,
n_jobs: int = -1,
verbose: bool = True,
) -> dict[str, list[str]]
Sync files between two filesystems by copying new files and deleting old ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
add_files
|
list[str]
|
List of file paths to add (copy from source to destination) |
required |
delete_files
|
list[str]
|
List of file paths to delete from destination |
required |
src_fs
|
AbstractFileSystem
|
Source filesystem (fsspec AbstractFileSystem) |
required |
dst_fs
|
AbstractFileSystem
|
Destination filesystem (fsspec AbstractFileSystem) |
required |
src_path
|
str
|
Base path in source filesystem. Default is root (''). |
''
|
dst_path
|
str
|
Base path in destination filesystem. Default is root (''). |
''
|
server_side
|
bool
|
Whether to use server-side copy if supported. Default is False. |
False
|
chunk_size
|
int
|
Size of chunks to read/write files (in bytes). Default is 8MB. |
8 * 1024 * 1024
|
parallel
|
bool
|
Whether to perform copy/delete operations in parallel. Default is False. |
False
|
n_jobs
|
int
|
Number of parallel jobs if parallel=True. Default is -1 (all cores). |
-1
|
verbose
|
bool
|
Whether to show progress bars. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, list[str]]
|
Summary of added and deleted files |
Source code in src/fsspeckit/common/sync.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
fsspeckit.common.validate_path
¶
Validate a filesystem path for security issues.
Checks for: - Embedded null bytes and control characters - Path traversal attempts (../ sequences escaping base_dir) - Empty or whitespace-only paths
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to validate. |
required |
base_dir
|
str | None
|
Optional base directory. If provided, the path must resolve to a location within this directory (prevents path traversal). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The validated path (unchanged if valid). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path contains forbidden characters, is empty, or escapes the base directory. |
Examples:
Source code in src/fsspeckit/common/security.py
fsspeckit.common.validate_compression_codec
¶
Validate that a compression codec is in the allowed set.
This prevents injection of arbitrary values into SQL queries or filesystem operations that accept codec parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codec
|
str
|
The compression codec name to validate. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The validated codec name (lowercased). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the codec is not in the allowed set. |
Examples:
Source code in src/fsspeckit/common/security.py
fsspeckit.common.scrub_credentials
¶
Remove or mask credential-like values from a string.
This is intended for use before logging error messages that might contain sensitive information like access keys or tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The string to scrub. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The string with credential-like values replaced with [REDACTED]. |
Examples:
Source code in src/fsspeckit/common/security.py
fsspeckit.common.scrub_exception
¶
Scrub credentials from an exception's string representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
BaseException
|
The exception to scrub. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A scrubbed string representation of the exception. |
Source code in src/fsspeckit/common/security.py
fsspeckit.common.safe_format_error
¶
safe_format_error(
operation: str,
path: str | None = None,
error: BaseException | None = None,
**context: Any,
) -> str
Format an error message with credentials scrubbed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
str
|
Description of the operation that failed. |
required |
path
|
str | None
|
Optional path involved in the operation. |
None
|
error
|
BaseException | None
|
Optional exception that occurred. |
None
|
**context
|
Any
|
Additional context key-value pairs. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A formatted, credential-scrubbed error message. |
Source code in src/fsspeckit/common/security.py
fsspeckit.common.validate_columns
¶
Validate that requested columns exist in the schema.
This is a helper to prevent column injection in SQL-like operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
list[str] | None
|
List of column names to validate, or None. |
required |
valid_columns
|
list[str]
|
List of valid column names from the schema. |
required |
Returns:
| Type | Description |
|---|---|
list[str] | None
|
The validated columns list, or None if columns was None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any column is not in the valid set. |