vayu (top-level)¶
The names re-exported from vayu/__init__.py. Most users should import from here:
from vayu import (
Cache, CacheMissError, FileCache, MemoryCache, Pickler, Jsoner, Serializer,
Interval, TimeWindow,
L, configure_logging,
mem_cache, mem_cached,
retry, add_jitter, group, camel_or_space_to_snake,
time_now, timeit, ts_ms, from_timestamp, from_z_string,
local_datetime, utc_datetime, min_time, max_time, epoch_time,
to_human_readable_time,
install_pandas_extensions,
)
Vayu: async-first utilities for caching, time, parallelism, and pandas.
The base install keeps dependencies light. Pandas/plotly/numpy-backed helpers
live under vayu.pandas_utils, vayu.plotly_utils, and vayu.statistics and
require the vayulib[data] extra.
retry
¶
retry(
exception_to_check: Union[_ExcType, Tuple[_ExcType]],
tries: int = 4,
delay: float = 1,
backoff: float = 2,
logger: Logger = None,
)
Retry calling the decorated function using an exponential backoff. Asyncio compatible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception_to_check
|
Union[_ExcType, Tuple[_ExcType]]
|
the exception to check. Maybe a tuple of exceptions to check. |
required |
tries
|
int
|
number of times to try (not retry) before giving up |
4
|
delay
|
float
|
initial delay between retries in seconds |
1
|
backoff
|
float
|
backoff multiplier e.g. value of 2 will double the delay for each retry |
2
|
logger
|
Logger
|
logger to use. If None, print. |
None
|
Source code in vayu/common.py
Interval
dataclass
¶
A closed interval [start, end] with union / intersection / containment algebra.
Works on any comparable type — int, float, date, datetime.
Subclasses (e.g. TimeWindow) flow through operators automatically because
the dunder methods use self.__class__.
Single-point intervals (start == end) are allowed so that touching
endpoints like [1, 3] & [3, 5] produce [3, 3] instead of raising.
Attributes:
| Name | Type | Description |
|---|---|---|
start |
Comparable
|
Lower bound (inclusive). |
end |
Comparable
|
Upper bound (inclusive). |
intersection
¶
Return the overlapping sub-interval, or raise if there's no overlap.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the intervals don't overlap. |
Source code in vayu/interval.py
union
classmethod
¶
Return the smallest interval that contains all inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intervals
|
Sequence[Interval]
|
One or more intervals to union. |
required |
allow_gaps
|
bool
|
If False (the default), raise |
False
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
ValueError
|
If |
Source code in vayu/interval.py
TimeWindow
dataclass
¶
Bases: Interval
An Interval over datetimes/dates, with convenience constructors.
Inherits the full interval algebra (intersects, intersection,
union, & / |, containment, shifting). Both endpoints must be the
same type: both date or both datetime. For tz-aware datetimes, both
must have tzinfo or both must be naive.
Attributes:
| Name | Type | Description |
|---|---|---|
start |
Union[datetime, date, None]
|
Lower bound. Defaults to the Unix epoch when left unset. |
end |
Union[datetime, date, None]
|
Upper bound. Defaults to |
ahead
staticmethod
¶
ahead(
*,
t: datetime = None,
duration: timedelta = None,
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0
) -> TimeWindow
Return the window [t, t + duration] (looking forward from t).
Pass either duration directly or individual timedelta kwargs
(hours=..., minutes=..., etc.). t defaults to time_now().
Source code in vayu/time_utils.py
behind
staticmethod
¶
behind(
*,
t: datetime = None,
duration: timedelta = None,
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0
) -> TimeWindow
Return the window [t - duration, t] (looking back from t).
Pass either duration directly or individual timedelta kwargs.
t defaults to time_now().
Source code in vayu/time_utils.py
around
staticmethod
¶
around(
*,
t: datetime = None,
duration: timedelta = None,
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0
)
Return [t - duration, t + duration] (symmetric window around t).
Pass either duration directly or individual timedelta kwargs.
t defaults to time_now().
Source code in vayu/time_utils.py
from_date
staticmethod
¶
from_date(
year: int, month: int, day: int, tz=None
) -> TimeWindow
Return the window spanning a full calendar day (midnight → end of day).
tz defaults to UTC.
Source code in vayu/time_utils.py
from_timestamp
staticmethod
¶
from_timestamp(
start_ts: [int, float], end_ts: [int, float], tz=None
) -> TimeWindow
Return the window built from two Unix timestamps.
Each timestamp may be seconds or milliseconds (see from_timestamp).
Source code in vayu/time_utils.py
Cache
¶
Cache(serializer: Serializer)
Bases: ABC
Abstract TTL cache with sync and async @cached decorators.
Subclasses implement the backend (_read / _write / _delete, each
in sync and async form). Concrete implementations include FileCache and
MemoryCache.
Source code in vayu/cache.py
cached
¶
cached(
ttl: Union[timedelta, float],
prefix: str = None,
key: Union[str, Callable] = None,
serializer: Serializer = None,
log: bool = True,
)
Used as decorator to cache function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl
|
Union[timedelta, float]
|
cache expiry ttl |
required |
prefix
|
str
|
If set, gets prepended to the rest of the cache key, otherwise uses function, class, and module name to create prefix. |
None
|
key
|
Union[str, Callable]
|
|
None
|
serializer
|
Serializer
|
If not specified, default pickler serializer is used |
None
|
log
|
bool
|
If True, logs reports such as cache hit, miss etc. |
True
|
Source code in vayu/cache.py
CacheMissError
¶
Bases: Exception
Raised on cache miss or when a cached entry has expired.
FileCache
¶
FileCache(path: str, serializer: Serializer = None)
Bases: Cache
Persistent cache backed by files under a directory.
One file per key. Writes are atomic (write to a temp file in the same
directory, then replace). Note: cache keys become filenames, so custom
key= callables must return filesystem-legal strings (avoid /, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Directory to store cache files. Created if it doesn't exist. |
required |
serializer
|
Serializer
|
How to encode values. Defaults to |
None
|
Source code in vayu/cache.py
Jsoner
¶
Bases: Serializer
Serializer that uses JSON.
Uses orjson when installed (faster), otherwise falls back to the
standard-library json. Only handles JSON-serializable values.
MemoryCache
¶
Bases: Cache
In-process cache backed by a plain dict.
Uses a no-op serializer — values are stored by reference, not copied.
Volatile: everything is lost when the process exits. The module-level
mem_cache is an instance of this class, and mem_cached is a
shortcut to mem_cache.cached.
Source code in vayu/cache.py
Pickler
¶
Bases: Serializer
Serializer that uses pickle with the highest protocol.
Supports arbitrary Python objects but is not safe to read from untrusted sources.
Serializer
¶
Bases: ABC
Strategy for converting cached values to/from bytes.
add_jitter
¶
group
¶
Group elements of an iterable by a key function.
epoch_time
¶
from_timestamp
¶
from_timestamp(ts: float, tz=TZ) -> datetime
Convert a Unix timestamp to a tz-aware datetime.
Timestamps greater than 1e12 are treated as milliseconds (divided by 1000);
smaller values are treated as seconds. This lets you pass either unit without
worrying about the difference.
Source code in vayu/time_utils.py
from_z_string
¶
local_datetime
¶
local_datetime(
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
tz=TZ,
) -> datetime
Construct a datetime in the module TZ (or the given tz).
Source code in vayu/time_utils.py
max_time
¶
Return the latest datetime on the given date (23:59:59.999999). UTC by default.
min_time
¶
Return the earliest datetime on the given date (00:00:00). UTC by default.
time_now
¶
Return the current time as a tz-aware datetime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
with_ms
|
bool
|
Keep microseconds. Default is to truncate to whole seconds. |
False
|
local
|
bool
|
If True, use the module |
True
|
Source code in vayu/time_utils.py
timeit
¶
Decorator that prints how long the wrapped function took.
Useful for quick scripts. For library-level instrumentation, wire your own
logging around the call instead — this helper uses print.
Source code in vayu/time_utils.py
to_human_readable_time
¶
Format a duration as a compact human string (e.g. 1h2m3s).
Accepts a timedelta or a number of seconds. Returns "0s" for zero
and "invalid-time" for negative values.
Source code in vayu/time_utils.py
ts_ms
¶
utc_datetime
¶
utc_datetime(
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
) -> datetime
Construct a UTC datetime. Convenience wrapper over datetime(..., tzinfo=UTC).
Source code in vayu/time_utils.py
configure_logging
¶
configure_logging(
level: Optional[str] = None,
tz: Optional[str] = None,
stream: IO = stdout,
fmt: str = "[%(asctime)s] %(levelname)s> %(message)s",
) -> None
Configure the vayu logger with a stdout handler and timezone-aware timestamps.
Off by default so that importing the library does not mutate global logging state. Call once at application startup to opt in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
Optional[str]
|
log level (default: env var LOG_LEVEL, else "INFO"). |
None
|
tz
|
Optional[str]
|
IANA timezone for timestamps (default: env var TZ, else "UTC"). |
None
|
stream
|
IO
|
handler output stream. |
stdout
|
fmt
|
str
|
log record format. |
'[%(asctime)s] %(levelname)s> %(message)s'
|
Source code in vayu/log.py
install_pandas_extensions
¶
Attach select convenience methods to pandas.DataFrame and pandas.Series.
Opt-in because it monkey-patches pandas globally. Call once at application
startup if you want df.select(...) and series.select(...). Requires the
vayulib[data] extra.