anyenv
Class info¶
Re-exported classes¶
| Class | Module | Description |
|---|---|---|
| HttpError | anyenv.download.exceptions | Base class for HTTP errors. |
| HttpResponse | anyenv.download.base | An HTTP response with its body already read. |
| HttpSession | anyenv.download.session | One httpx client for many requests (connection reuse); see http_session. |
| JsonDumpError | anyenv.json_tools.base | Unified exception for all JSON serialization errors. |
| JsonLoadError | anyenv.json_tools.base | Unified exception for all JSON parsing errors. |
| MultiEventHandler | anyenv.calling.multieventhandler | Manages multiple callbacks/event handlers with various execution modes. |
| ProcessManager | anyenv.process_manager.process_manager | Manages background processes for an agent pool. |
| ProcessOutput | anyenv.process_manager.models | Output from a running process. |
| RequestError | anyenv.download.exceptions | Exception raised when a request fails due to network or connection issues. |
| ResponseError | anyenv.download.exceptions | Exception raised when a response contains an error status code. |
| RunningProcess | anyenv.process_manager.process | Represents a running background process. |
| ThreadGroup | anyenv.calling.threadgroup | Class that executes functions in parallel, with TaskGroup-like API. |
| TomlDumpError | anyenv.toml_tools.base | Unified exception for all TOML serialization errors. |
| TomlLoadError | anyenv.toml_tools.base | Unified exception for all TOML parsing errors. |
🛈 DocStrings¶
AnyEnv: main package.
Compatibility layer for some basic operations to allow painless operation in PyOdide and Python pre-releases.
DEFAULT_TIMEOUT
module-attribute
¶
Default per-operation HTTP timeout in seconds (connect is capped at 10 s).
HttpError
¶
Bases: Exception
Base class for HTTP errors.
Source code in src/anyenv/download/exceptions.py
HttpResponse
¶
An HTTP response with its body already read.
A thin wrapper over the response of whichever httpx flavour is installed (httpx2 or httpx), so callers don't depend on the flavour.
Source code in src/anyenv/download/base.py
headers
property
¶
Response headers (case-insensitive, read-only; repeated headers joined by commas).
json
¶
validated_json
¶
Response body parsed as JSON and validated against a type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_type
|
type[T]
|
The type to validate the response against |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If validation fails |
Source code in src/anyenv/download/base.py
HttpSession
¶
One httpx client for many requests (connection reuse); see http_session.
base_url resolves relative URLs. The session's headers go with requests
to base_url (relative URLs and absolute ones under it); without a
base_url, with every request through the session, including those of
libraries that use anyenv's helpers inside the async with block.
Source code in src/anyenv/download/session.py
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 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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | |
accepts
¶
Whether a helper call with these cache options can go through this session.
Source code in src/anyenv/download/session.py
aclose
async
¶
download
async
¶
download(
url: str,
path: StrPath,
*,
headers: HeaderType | None = None,
progress_callback: ProgressCallback | None = None,
timeout: float | None = _UNSET,
) -> None
Stream a URL into a file (<path>.part until complete).
The read timeout applies per read (not to the whole download), so large
downloads keep working as long as data keeps arriving; pass
timeout=None to disable timeouts altogether.
Source code in src/anyenv/download/session.py
get
async
¶
get(url: str, **options: Unpack[RequestOptions]) -> HttpResponse
get_bytes
async
¶
get_bytes(url: str, **options: Unpack[RequestOptions]) -> bytes
get_json
async
¶
get_json(
url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
) -> T
GET a URL and return the body parsed as JSON (validated if return_type).
Source code in src/anyenv/download/session.py
get_text
async
¶
get_text(url: str, **options: Unpack[RequestOptions]) -> str
post
async
¶
post(
url: str,
*,
json: Any = None,
data: Any = None,
files: FilesType | None = None,
**options: Unpack[RequestOptions],
) -> HttpResponse
Send a POST request.
Source code in src/anyenv/download/session.py
post_json
async
¶
post_json(
url: str,
json_data: Any,
*,
files: FilesType | None = None,
return_type: type[T] | None = None,
**options: Unpack[RequestOptions],
) -> T
POST JSON (form data with files) and return the response parsed as JSON.
Source code in src/anyenv/download/session.py
request
async
¶
request(
method: Method,
url: str,
*,
json: Any = None,
data: Any = None,
files: FilesType | None = None,
**options: Unpack[RequestOptions],
) -> HttpResponse
Send a request; returns the response once its body is read.
Raises:
| Type | Description |
|---|---|
RequestError
|
The request failed (connection, timeout) |
ResponseError
|
The response has a 4xx / 5xx status |
Source code in src/anyenv/download/session.py
resolve
¶
The absolute URL of a request (relative URLs are appended to base_url).
usable_here
¶
Whether this context can use the client: it's open and on its event loop.
(Another loop may see the session through a copied context, e.g. in
run_sync; a client can't be shared between loops.)
Source code in src/anyenv/download/session.py
JsonDumpError
¶
JsonLoadError
¶
Bases: Exception
Unified exception for all JSON parsing errors.
Source code in src/anyenv/json_tools/base.py
source_path
property
¶
Path to the source file that caused the error.
format
¶
Format error with source context for display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context_lines
|
int
|
Number of lines to show before/after the error line. |
2
|
use_color
|
bool
|
Whether to include ANSI color codes. |
True
|
Source code in src/anyenv/json_tools/base.py
MultiEventHandler
¶
Manages multiple callbacks/event handlers with various execution modes.
Provides a unified interface for executing multiple callbacks either sequentially, in parallel, or as background tasks, with support for dynamic handler management and optional debouncing. Sync functions are automatically wrapped to work with the async interface.
The generic parameters HandlerT and Mode provide type safety: - HandlerT: callable type (function signature) - Mode: execution mode literal for return type inference
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handlers
|
Sequence[HandlerT] | HandlerT | None
|
Initial list of async or sync callable event handlers, or single handler |
None
|
mode
|
Mode
|
Execution mode - "sequential", "parallel", or "task" |
'parallel'
|
debounce_delay
|
float | None
|
Optional delay in seconds for debouncing rapid calls |
None
|
Example
from collections.abc import Awaitable
from typing import Callable, Literal
async def async_handler(x: int, y: str) -> str:
return f"Async Handler: {x}, {y}"
def sync_handler(x: int, y: str) -> str:
return f"Sync Handler: {x}, {y}"
# Type-safe handler with task mode
Handler = Callable[[int, str], str | Awaitable[str]]
manager = MultiEventHandler[Handler, Literal["task"]](
[async_handler, sync_handler],
"task",
debounce_delay=0.1
)
tasks: list[asyncio.Task[Any]] = await manager(42, "test")
Source code in src/anyenv/calling/multieventhandler.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
__bool__
¶
__call__
async
¶
Execute all handlers with the configured mode and debouncing.
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
|
Source code in src/anyenv/calling/multieventhandler.py
__len__
¶
__repr__
¶
Return string representation showing handlers, mode, and debounce.
Source code in src/anyenv/calling/multieventhandler.py
add_handler
¶
Add a new handler to the manager.
Both sync and async handlers are supported.
Source code in src/anyenv/calling/multieventhandler.py
call_handlers
async
¶
Execute handlers with explicit mode, bypassing configured mode and debouncing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ExecutionMode
|
Execution mode to use for this call |
required |
*args
|
Any
|
Arguments to pass to handlers |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to handlers |
{}
|
Returns:
| Type | Description |
|---|---|
list[Any] | list[Task[Any]]
|
|
list[Any] | list[Task[Any]]
|
|
Source code in src/anyenv/calling/multieventhandler.py
clear
¶
remove_handler
¶
Remove a handler from the manager.
Note: For sync handlers, you must pass the original sync function, not the wrapped async version.
Source code in src/anyenv/calling/multieventhandler.py
ProcessManager
¶
Bases: ProcessManagerProtocol
Manages background processes for an agent pool.
Source code in src/anyenv/process_manager/process_manager.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 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 280 281 | |
__init__
¶
cleanup
async
¶
Clean up all processes.
Source code in src/anyenv/process_manager/process_manager.py
get_output
async
¶
get_output(process_id: str) -> ProcessOutput
Get current output from a process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_id
|
str
|
Process identifier |
required |
Returns:
| Type | Description |
|---|---|
ProcessOutput
|
Current process output |
Raises:
| Type | Description |
|---|---|
ValueError
|
If process not found |
Source code in src/anyenv/process_manager/process_manager.py
get_process_info
async
¶
Get information about a process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_id
|
str
|
Process identifier |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Process information dict |
Raises:
| Type | Description |
|---|---|
ValueError
|
If process not found |
Source code in src/anyenv/process_manager/process_manager.py
kill_process
async
¶
Kill a running process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_id
|
str
|
Process identifier |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If process not found |
Source code in src/anyenv/process_manager/process_manager.py
list_processes
async
¶
release_process
async
¶
Release resources for a process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_id
|
str
|
Process identifier |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If process not found |
Source code in src/anyenv/process_manager/process_manager.py
start_process
async
¶
start_process(
command: str,
args: list[str] | None = None,
cwd: str | Path | None = None,
env: dict[str, str] | None = None,
output_limit: int | None = None,
) -> str
Start a background process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
Command to execute. When args is None/empty, this is interpreted as a shell command string (supporting pipes, redirects, etc.). When args is provided, command is the program name executed directly. |
required |
args
|
list[str] | None
|
Command arguments. If provided, command is executed directly with these arguments. If None/empty, command is run through the shell. |
None
|
cwd
|
str | Path | None
|
Working directory |
None
|
env
|
dict[str, str] | None
|
Environment variables (added to current env) |
None
|
output_limit
|
int | None
|
Maximum bytes of output to retain |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Process ID for tracking |
Raises:
| Type | Description |
|---|---|
OSError
|
If process creation fails |
Source code in src/anyenv/process_manager/process_manager.py
wait_for_exit
async
¶
Wait for process to complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_id
|
str
|
Process identifier |
required |
Returns:
| Type | Description |
|---|---|
int
|
Exit code |
Raises:
| Type | Description |
|---|---|
ValueError
|
If process not found |
Source code in src/anyenv/process_manager/process_manager.py
ProcessOutput
dataclass
¶
RequestError
¶
Bases: HttpError
Exception raised when a request fails due to network or connection issues.
Source code in src/anyenv/download/exceptions.py
ResponseError
¶
Bases: HttpError
Exception raised when a response contains an error status code.
Source code in src/anyenv/download/exceptions.py
RunningProcess
dataclass
¶
Represents a running background process.
Source code in src/anyenv/process_manager/process.py
add_output
¶
Add output to buffers, applying size limits.
Source code in src/anyenv/process_manager/process.py
get_output
¶
get_output() -> ProcessOutput
Get current process output.
Source code in src/anyenv/process_manager/process.py
is_running
async
¶
kill
async
¶
ThreadGroup
¶
Class that executes functions in parallel, with TaskGroup-like API.
Source code in src/anyenv/calling/threadgroup.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 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 | |
__aenter__
async
¶
__aenter__() -> ThreadGroup[R]
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit the async context manager, waiting without blocking the event loop.
Source code in src/anyenv/calling/threadgroup.py
__enter__
¶
__enter__() -> ThreadGroup[R]
__exit__
¶
__exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit the context manager: wait for all tasks and shut the executor down.
Results are collected in spawn order. On the first failure (with
raise_exceptions) tasks that haven't started are cancelled, the running
ones are waited for, then the first failure in spawn order is raised.
Source code in src/anyenv/calling/threadgroup.py
__init__
¶
__init__(
max_workers: int | None = None, raise_exceptions: bool = True, preserve_context: bool = False
) -> None
Thread task group that executes functions in parallel.
Supports both sync and async context managers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_workers
|
int | None
|
Maximum number of worker threads |
None
|
raise_exceptions
|
bool
|
If True, raises exceptions from tasks |
True
|
preserve_context
|
bool
|
If True, preserves context variables across threads |
False
|
Source code in src/anyenv/calling/threadgroup.py
shutdown
¶
spawn
¶
Submit a task immediately to the executor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., R]
|
The function to execute |
required |
*args
|
Any
|
Positional arguments to pass to the function |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
| Type | Description |
|---|---|
Future[R]
|
Future object representing the execution of the function |
Source code in src/anyenv/calling/threadgroup.py
TomlDumpError
¶
TomlLoadError
¶
Bases: Exception
Unified exception for all TOML parsing errors.
Source code in src/anyenv/toml_tools/base.py
source_path
property
¶
Path to the source file that caused the error.
format
¶
Format error with source context for display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context_lines
|
int
|
Number of lines to show before/after the error line. |
2
|
use_color
|
bool
|
Whether to include ANSI color codes. |
True
|
Source code in src/anyenv/toml_tools/base.py
call_and_gather
async
¶
call_and_gather(
callables: Sequence[Callable[..., Awaitable[T]]],
args: tuple[Any, ...] | Sequence[tuple[Any, ...]],
kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None,
return_exceptions: Literal[True],
limit: int | None = None,
) -> Sequence[T | BaseException]
call_and_gather(
callables: Sequence[Callable[..., Awaitable[T]]],
args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
return_exceptions: bool = False,
limit: int | None = None,
) -> Sequence[T | BaseException]
Call multiple callables and gather their results concurrently.
This is a helper for the common pattern of calling multiple handlers/functions and gathering their results concurrently. Supports two modes:
- Broadcast mode: Same args/kwargs for all callables
- Per-callable mode: Different args/kwargs for each callable
Uses aioitertools.asyncio.gather if available for limit support, falls back to the local gather implementation otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callables
|
Sequence[Callable[..., Awaitable[T]]]
|
Sequence of callable objects that return awaitables |
required |
args
|
tuple[Any, ...] | Sequence[tuple[Any, ...]]
|
Single tuple (broadcast) or sequence of tuples (per-callable) |
()
|
kwargs
|
dict[str, Any] | Sequence[dict[str, Any]] | None
|
Single dict (broadcast) or sequence of dicts (per-callable) |
None
|
return_exceptions
|
bool
|
If True, exceptions are returned instead of raised |
False
|
limit
|
int | None
|
Maximum concurrent tasks (None for unlimited, only with aioitertools) |
None
|
Returns:
| Type | Description |
|---|---|
Sequence[T | BaseException]
|
A sequence of results in the same order as the input callables |
Source code in src/anyenv/async_run.py
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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
create_process
async
¶
create_process(
command: str | PathLike[str],
*args: str | PathLike[str],
stdin: Mode | None = None,
stdout: Mode | None = None,
stderr: Mode | None = None,
limit: int = 10 * 1024 * 1024,
env: dict[str, str] | None = None,
cwd: str | PathLike[str] | None = None,
start_new_session: bool = False,
) -> Process
Small create_subprocess_exec wrapper.
Source code in src/anyenv/processes.py
create_shell_process
async
¶
create_shell_process(
command: str,
stdin: Mode | None = None,
stdout: Mode | None = None,
stderr: Mode | None = None,
limit: int = 10 * 1024 * 1024,
cwd: str | PathLike[str] | None = None,
env: dict[str, str] | None = None,
start_new_session: bool = False,
) -> Process
Small create_subprocess_shell wrapper.
Source code in src/anyenv/processes.py
download_sync
¶
download_sync(
url: str,
path: StrPath,
*,
headers: HeaderType | None = None,
progress_callback: ProgressCallback | None = None,
timeout: float | None = _UNSET,
cache: bool | None = None,
cache_dir: StrPath | None = None,
cache_ttl: int | str | None = None,
) -> None
Synchronous version of download.
Source code in src/anyenv/download/functional.py
dump_json
¶
dump_json(
data: Any,
indent: bool = False,
naive_utc: bool = False,
serialize_numpy: bool = False,
sort_keys: bool = False,
backend: BackendType = "auto",
) -> str
Serialize data to a JSON string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to serialize |
required |
indent
|
bool
|
Whether to format the output with indentation |
False
|
naive_utc
|
bool
|
Whether to interpret naive datetime objects as UTC |
False
|
serialize_numpy
|
bool
|
Whether to serialize numpy arrays |
False
|
sort_keys
|
bool
|
Sort dictionary keys |
False
|
backend
|
BackendType
|
JSON backend to use for serialization |
'auto'
|
Returns:
| Type | Description |
|---|---|
str
|
The serialized JSON string |
Raises:
| Type | Description |
|---|---|
JsonDumpError
|
If serialization fails |
Source code in src/anyenv/json_tools/__init__.py
dump_toml
¶
Serialize data to a TOML string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to serialize |
required |
pretty
|
bool
|
Whether to format the output with pretty formatting |
False
|
backend
|
BackendType
|
TOML backend to use for serialization |
'auto'
|
Returns:
| Type | Description |
|---|---|
str
|
The serialized TOML string |
Raises:
| Type | Description |
|---|---|
TomlDumpError
|
If serialization fails |
Source code in src/anyenv/toml_tools/__init__.py
function_spawner
¶
function_spawner(func: Callable[P, Awaitable[T]]) -> AsyncExecutor[P, T]
function_spawner(func: Callable[P, AsyncIterator[T]]) -> AsyncIteratorExecutor[P, T]
function_spawner(
func: Callable[P, Awaitable[T] | AsyncIterator[T]],
) -> AsyncExecutor[P, T] | AsyncIteratorExecutor[P, T]
Decorator for standalone async functions and async generators.
Usage
@function_spawner async def my_func(x: int) -> str: return str(x)
@function_spawner async def my_generator(x: int): for i in range(x): yield i
Usage:¶
result = my_func.sync(42) # Sync for item in my_generator.sync(3): # iteration print(item)
Source code in src/anyenv/calling/async_executor.py
gather
async
¶
gather(
*coros_or_futures: Awaitable[T], return_exceptions: bool = False
) -> Sequence[T | Exception]
Run awaitables concurrently using anyio's task groups.
Like asyncio.gather, a failure raises the failing awaitable's own exception
(the first one, if several fail), not an ExceptionGroup; the others are
cancelled. Cancellation is never returned as a result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*coros_or_futures
|
Awaitable[T]
|
Awaitables (coroutines or futures) to run concurrently |
()
|
return_exceptions
|
bool
|
If True, exceptions are returned instead of raised |
False
|
Returns:
| Type | Description |
|---|---|
Sequence[T | Exception]
|
A list of results in the same order as the input awaitables |
Source code in src/anyenv/async_run.py
get
async
¶
get(
url: str,
*,
params: ParamsType | None = None,
headers: HeaderType | None = None,
timeout: float | None = _UNSET,
cache: bool | None = None,
cache_dir: StrPath | None = None,
cache_ttl: int | str | None = None,
api_key: str | SecretStr | None = None,
auth_type: AuthType = "bearer",
auth_username: str | None = None,
auth_header_name: str | None = None,
) -> HttpResponse
Make a GET request (options as for request).
Source code in src/anyenv/download/functional.py
get_bytes
async
¶
get_bytes(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> bytes
GET a URL and return the body as bytes (options as for request).
get_bytes_sync
¶
get_bytes_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> bytes
Synchronous version of get_bytes.
get_json
async
¶
get_json(
url: str, *, return_type: type[T] | None = None, **kwargs: Unpack[DataRetrievalOptions]
) -> T
GET a URL and return the body parsed as JSON (options as for request).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to request |
required |
return_type
|
type[T] | None
|
Type to validate the data against (pydantic models, dataclasses, TypedDicts, ...); without it the data is returned as parsed |
None
|
kwargs
|
Unpack[DataRetrievalOptions]
|
Options as for |
{}
|
Source code in src/anyenv/download/functional.py
get_json_sync
¶
get_json_sync(
url: str, *, return_type: type[T] | None = None, **kwargs: Unpack[DataRetrievalOptions]
) -> T
Synchronous version of get_json.
Source code in src/anyenv/download/functional.py
get_os_command_provider
¶
get_os_command_provider(
system: Literal["Windows", "Darwin", "Linux"] | None = None,
) -> OSCommandProvider
Auto-detect OS and return appropriate command provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
Literal['Windows', 'Darwin', 'Linux'] | None
|
The system to use. If None, the current system is used. |
None
|
Returns:
| Type | Description |
|---|---|
OSCommandProvider
|
OS-specific command provider based on current platform |
Source code in src/anyenv/os_commands/providers.py
get_sync
¶
get_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> HttpResponse
get_text
async
¶
get_text(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> str
GET a URL and return the body as text (options as for request).
get_text_sync
¶
get_text_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> str
Synchronous version of get_text.
http_session
async
¶
http_session(
*,
base_url: str | None = None,
headers: HeaderType | None = None,
cache: bool = False,
cache_dir: StrPath | None = None,
cache_ttl: int | str | None = None,
cache_backend: CacheType = "file",
timeout: float | None = _UNSET,
) -> AsyncGenerator[HttpSession]
Open one HTTP client for many requests.
While the block runs, the module-level helpers (anyenv.get_json(...) etc.)
in this context use the session too; leaving it restores the outer session (if
any). Helper calls asking for other cache settings get a client of their own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str | None
|
Prefix for relative URLs; the session's headers only go to it |
None
|
headers
|
HeaderType | None
|
Headers for every request (see |
None
|
cache
|
bool
|
Cache responses (hishel; keyed by URL and credentials) |
False
|
cache_dir
|
StrPath | None
|
Directory of the cache database (default: the user cache dir) |
None
|
cache_ttl
|
int | str | None
|
How long cached responses are used: seconds or e.g. "1h", "2d" |
None
|
cache_backend
|
CacheType
|
"file" (an SQLite file in |
'file'
|
timeout
|
float | None
|
Default timeout per request in seconds (default: |
_UNSET
|
Example
Source code in src/anyenv/download/session.py
install
async
¶
Install a package using the appropriate installer for the current environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_name
|
str
|
Name of the package to install. |
required |
version
|
str | None
|
Optional version specifier. |
None
|
upgrade
|
bool
|
Whether to upgrade an existing package. |
False
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If no suitable installer is available. |
Source code in src/anyenv/package_install/functional.py
install_sync
¶
Synchronous version of install.
Source code in src/anyenv/package_install/functional.py
load_json
¶
load_json(
data: str | bytes | TextIOWrapper, return_type: type[T], backend: BackendType = "auto"
) -> T
load_json(
data: str | bytes | TextIOWrapper,
return_type: type[Any] | UnionType | None = None,
backend: BackendType = "auto",
) -> Any
Load JSON data with optional type validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str | bytes | TextIOWrapper
|
The JSON data to parse (string, bytes, or file-like object) |
required |
return_type
|
type[Any] | UnionType | None
|
Optional type to validate the data against |
None
|
backend
|
BackendType
|
JSON backend to use for parsing |
'auto'
|
Returns:
| Type | Description |
|---|---|
Any
|
The parsed and validated data |
Raises:
| Type | Description |
|---|---|
JsonLoadError
|
If parsing fails |
TypeError
|
If validation against return_type fails |
Source code in src/anyenv/json_tools/__init__.py
load_toml
¶
load_toml(
data: str | bytes | TextIOWrapper | Path,
return_type: type[T] | None = None,
backend: BackendType = "auto",
) -> T
Load TOML data with optional type validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str | bytes | TextIOWrapper | Path
|
The TOML data to parse (string, bytes, file-like object, or Path) |
required |
return_type
|
type[T] | None
|
Optional type to validate the data against |
None
|
backend
|
BackendType
|
TOML backend to use for parsing |
'auto'
|
Returns:
| Type | Description |
|---|---|
T
|
The parsed and validated data |
Raises:
| Type | Description |
|---|---|
TomlLoadError
|
If parsing fails |
TypeError
|
If validation against return_type fails |
Source code in src/anyenv/toml_tools/__init__.py
method_spawner
¶
method_spawner(func: Callable[Concatenate[Any, P], Awaitable[T]]) -> AsyncExecutor[P, T]
method_spawner(
func: Callable[Concatenate[Any, P], AsyncIterator[T]],
) -> AsyncIteratorExecutor[P, T]
method_spawner(
func: Callable[Concatenate[Any, P], Awaitable[T] | AsyncIterator[T]],
) -> AsyncExecutor[P, T] | AsyncIteratorExecutor[P, T]
Decorator for async methods and async generator methods.
Usage
class MyClass: @method_spawner async def my_method(self, x: int) -> str: return str(x)
@method_spawner
async def my_generator(self, x: int):
for i in range(x):
yield i
Usage:¶
obj = MyClass() result = obj.my_method.sync(42) # Sync for item in obj.my_generator.sync(3): # iteration print(item)
Source code in src/anyenv/calling/async_executor.py
open_in_playground
¶
open_in_playground(
file: ModuleType | str | PathLike[str],
title: str = "Open in Pydantic Playground",
dependencies: list[str] | None = None,
open_browser: bool = True,
) -> str
Create a link to Pydantic playground with a pre-populated file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
ModuleType | str | PathLike[str]
|
The file to include in the playground. Can be: - A module - A file path |
required |
title
|
str
|
The title of the link (not used in URL generation) |
'Open in Pydantic Playground'
|
dependencies
|
list[str] | None
|
List of package dependencies to include as PEP 723 header |
None
|
open_browser
|
bool
|
Whether to automatically open the link in a browser |
True
|
Returns:
| Type | Description |
|---|---|
str
|
A URL string pointing to the Pydantic playground |
Source code in src/anyenv/testing.py
post
async
¶
post(
url: str,
*,
params: ParamsType | None = None,
headers: HeaderType | None = None,
json: Any = None,
data: Any = None,
files: FilesType | None = None,
timeout: float | None = _UNSET,
cache: bool | None = None,
cache_dir: StrPath | None = None,
cache_ttl: int | str | None = None,
api_key: str | SecretStr | None = None,
auth_type: AuthType = "bearer",
auth_username: str | None = None,
auth_header_name: str | None = None,
) -> HttpResponse
Make a POST request (options as for request).
Source code in src/anyenv/download/functional.py
post_json
async
¶
post_json(
url: str,
json_data: Any,
*,
files: FilesType | None = None,
return_type: type[T] | None = None,
**kwargs: Unpack[DataRetrievalOptions],
) -> T
POST JSON and return the response parsed as JSON (options as for request).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to request |
required |
json_data
|
Any
|
Data sent as JSON body (as form fields when |
required |
files
|
FilesType | None
|
Files to upload (multipart) |
None
|
return_type
|
type[T] | None
|
Type to validate the response against |
None
|
kwargs
|
Unpack[DataRetrievalOptions]
|
Options as for |
{}
|
Source code in src/anyenv/download/functional.py
post_json_sync
¶
post_json_sync(
url: str,
json_data: Any,
*,
files: FilesType | None = None,
return_type: type[T] | None = None,
**kwargs: Unpack[DataRetrievalOptions],
) -> T
Synchronous version of post_json.
Source code in src/anyenv/download/functional.py
post_sync
¶
post_sync(
url: str,
*,
json: Any = None,
data: Any = None,
files: FilesType | None = None,
**kwargs: Unpack[DataRetrievalOptions],
) -> HttpResponse
Synchronous version of post.
Source code in src/anyenv/download/functional.py
request
async
¶
request(
method: Method,
url: str,
*,
params: ParamsType | None = None,
headers: HeaderType | None = None,
json: Any = None,
data: Any = None,
files: FilesType | None = None,
timeout: float | None = _UNSET,
cache: bool | None = None,
cache_dir: StrPath | None = None,
cache_ttl: int | str | None = None,
api_key: str | SecretStr | None = None,
auth_type: AuthType = "bearer",
auth_username: str | None = None,
auth_header_name: str | None = None,
) -> HttpResponse
Make an HTTP request; the response's body is read already.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
Method
|
HTTP method to use |
required |
url
|
str
|
URL to request (relative URLs resolve against the session's base_url) |
required |
params
|
ParamsType | None
|
Query parameters |
None
|
headers
|
HeaderType | None
|
Request headers |
None
|
json
|
Any
|
JSON body |
None
|
data
|
Any
|
Form data or raw body |
None
|
files
|
FilesType | None
|
Files to upload (multipart) |
None
|
timeout
|
float | None
|
Timeout in seconds. When omitted, uses the open session's timeout,
or |
_UNSET
|
cache
|
bool | None
|
Cache responses (default: as the open session does, else no) |
None
|
cache_dir
|
StrPath | None
|
Directory of the cache database |
None
|
cache_ttl
|
int | str | None
|
How long cached responses are used: seconds or e.g. "1h", "2d" |
None
|
api_key
|
str | SecretStr | None
|
API key or token for authentication |
None
|
auth_type
|
AuthType
|
How the api_key is sent ("bearer", "basic", "header", "query") |
'bearer'
|
auth_username
|
str | None
|
Username for basic authentication |
None
|
auth_header_name
|
str | None
|
Header name for auth_type="header" (default: X-API-Key) |
None
|
Raises:
| Type | Description |
|---|---|
RequestError
|
The request failed (connection, timeout) |
ResponseError
|
The response has a 4xx / 5xx status |
Source code in src/anyenv/download/functional.py
request_sync
¶
request_sync(
method: Method,
url: str,
*,
json: Any = None,
data: Any = None,
files: FilesType | None = None,
**kwargs: Unpack[DataRetrievalOptions],
) -> HttpResponse
Synchronous version of request.
Source code in src/anyenv/download/functional.py
run_in_thread
async
¶
run_in_thread(
func: Callable[[*PosArgsT], T_Retval],
*args: *PosArgsT,
abandon_on_cancel: bool = False,
cancellable: bool | None = None,
limiter: Any = None,
**kwargs: Any,
) -> T_Retval
Run a function in a separate thread using anyio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[*PosArgsT], T_Retval]
|
The function to run in a thread |
required |
*args
|
*PosArgsT
|
Positional arguments to pass to the function |
()
|
abandon_on_cancel
|
bool
|
Whether to abandon execution on cancellation |
False
|
cancellable
|
bool | None
|
Whether the operation can be cancelled |
None
|
limiter
|
Any
|
Optional capacity limiter for limiting concurrent threads |
None
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
| Type | Description |
|---|---|
T_Retval
|
The return value of the function |
Source code in src/anyenv/async_run.py
run_sync
¶
Run a coroutine synchronously.
This function uses anyio to run a coroutine in a synchronous context: outside an event loop with anyio's run function directly; inside one (an async frame calling sync code) in a new thread. The latter blocks the calling loop until the coroutine is done.
Context variables are properly propagated between threads in all cases.
Example:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coro
|
Coroutine[Any, Any, T]
|
The coroutine to run synchronously |
required |
Returns:
| Type | Description |
|---|---|
T
|
The result of the coroutine |
Source code in src/anyenv/async_run.py
run_sync_in_thread
¶
Run a coroutine synchronously in a new thread.
This function creates a new thread to run the coroutine with anyio. Context variables are properly propagated between threads. This is useful when you need to run async code in a context where you can't use the current event loop (e.g., inside an async frame).
Example:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coro
|
Coroutine[Any, Any, T]
|
The coroutine to run synchronously |
required |
Returns:
| Type | Description |
|---|---|
T
|
The result of the coroutine |