Skip to main content

AnyEnv

PyPI License Package status Monthly downloads Distribution format Wheel availability Python version Implementation Releases Github Contributors Github Forks Github Issues Github Issues Github Watchers Github Stars Github Repository size Github last commit Github release date Github language count Github commits this month Package status PyUp

Read the documentation!

Overview

AnyEnv provides a unified interface for executing code across different environments - local, subprocess, Docker containers, remote sandboxes, and more. Choose the right execution environment for your needs without changing your code.

Getting Started

Install anyenv with its HTTP extra. HTTP goes through httpx2, pydantic's maintained fork of httpx:

pip install "anyenv[httpx2]"  # recommended
pip install "anyenv[httpx]"  # legacy: original httpx, kept for compatibility

When both are installed, httpx2 is used. anyenv itself never needs the legacy httpx package once httpx2 is installed. Under Pyodide (sys.platform == "emscripten"), the client sends its requests through the browser's fetch.

HTTP

import anyenv

# GET: the response's body is read already, its accessors are plain attributes
response = await anyenv.get("https://api.example.com/data")
print(response.status_code, response.reason, response.headers["Content-Type"])  # case-insensitive
print(response.text)  # str
print(response.content)  # bytes
print(response.json())  # parsed JSON
user = response.validated_json(User)  # validated (pydantic models, dataclasses, ...)

# The body directly
data = await anyenv.get_json("https://api.example.com/users")
text = await anyenv.get_text("https://example.com/page.html")
blob = await anyenv.get_bytes("https://example.com/image.png")

# POST
response = await anyenv.post("https://api.example.com/create", json={"name": "test"})
result = await anyenv.post_json("https://api.example.com/api", {"key": "value"})

# Downloads (written to <path>.part, renamed when complete)
await anyenv.download("https://example.com/file.zip", "file.zip", progress_callback=print)

# Authentication: bearer (default), basic, a header or a query parameter
data = await anyenv.get_json(url, api_key=token)
data = await anyenv.get_json(url, api_key=key, auth_type="header", auth_header_name="X-Key")

By default, every request and http_session() uses DEFAULT_TIMEOUT (30 s per operation, with connect limited to 10 s; for download(), the read timeout applies per read so large downloads keep working). Pass timeout=<seconds> to override or timeout=None to disable timeouts altogether; inside an http_session(), omitting timeout uses the session's timeout.

Sessions: one client for many requests

Without a session, every call opens (and closes) its own client: a new TCP and TLS connection per request. http_session() keeps one client open; while it is, the helpers above use it too, also when a library you call uses them:

async with anyenv.http_session(base_url="https://api.github.com", timeout=30) as s:
    repo = await s.get_json("/repos/phil65/anyenv")  # relative to base_url
    issues = await anyenv.get_json("/repos/phil65/anyenv/issues")  # same client
  • base_url resolves relative URLs; headers go with every request to base_url (without a base_url: with every request through the session).
  • Sessions nest: the innermost open one is used; leaving it restores the outer one. Tasks started inside a session inherit it (a ContextVar); other tasks don't see it.
  • A helper call asking for other cache settings than the session's (cache=, cache_dir=, cache_ttl=) uses a client of its own.
  • The session object has the same methods: request, get, post, get_json, get_text, get_bytes, post_json, download.

Caching

Responses can be cached with hishel, for a TTL anyenv sets (servers' Cache-Control: max-age=0 is ignored). Entries are keyed by URL and request headers, credentials included: one API key's response is never served for another.

data = await anyenv.get_json(url, cache=True, cache_ttl="1d")  # SQLite file in the user cache dir
async with anyenv.http_session(cache=True, cache_backend="memory"):  # for the session only
    ...

Synchronous versions

Every helper has a *_sync counterpart (get_sync, get_json_sync, download_sync, ...) with the same options. Each call runs on an event loop of its own, with its own client (also inside an http_session block).

Error handling

from anyenv import HttpError, RequestError, ResponseError

try:
    response = await anyenv.get("https://api.example.com/data")
except RequestError as e:  # connection failed, timeout
    print(f"Request failed: {e}")
except ResponseError as e:  # 4xx / 5xx; e.response has the body
    print(f"Server error {e.status_code}: {e.response.text}")

Migrating from 2.x

anyenv 3.0 has one HTTP stack (httpx) and synchronous response accessors:

2.x 3.0
await r.text(), await r.json(), await r.bytes() r.text, r.json(), r.content
await r.validated_json(T) r.validated_json(T)
backend=..., get_backend(), HttpBackend, BackendType gone: httpx2 (or httpx) only
anyenv[aiohttp], the pyodide backend gone: anyenv[httpx2]; Pyodide uses fetch through httpx
Session, backend.create_session() async with anyenv.http_session(...) as s:

The body helpers (get_json, get_text, post_json, ...) and their *_sync versions keep their API.

LSP diagnostics

DiagnosticRunner runs the CLI diagnostics of language servers (pyright, mypy, ty, ...); run_all(files, concurrency=n) runs up to n servers at once (default: one after another).

Package Installation

Programmatically install Python packages across environments:

from anyenv import install, install_sync

# Install packages asynchronously
await install("requests")
await install(["numpy", "pandas"])
await install("package>=1.0.0")

# Synchronous installation
install_sync("matplotlib")
install_sync(["scipy", "sklearn"])

# Install with specific options
await install("package", upgrade=True, user=True)

Async Utilities

Utilities for running async/sync code and managing concurrency:

from anyenv import run_sync, run_sync_in_thread, gather, call_and_gather

# Run async function from sync context
result = run_sync(async_function())

# Run sync function in thread from async context
result = await run_sync_in_thread(sync_function, arg1, arg2)

# Enhanced gather with better error handling
results = await gather(async_func1(), async_func2(), async_func3(), return_exceptions=True)

# Call function and gather results
func_results = await call_and_gather(
    my_function,
    [arg1, arg2, arg3],  # Arguments to call function with
    max_workers=5,
)

Threading and Concurrency

Manage concurrent operations with ThreadGroup and spawners:

from anyenv import ThreadGroup, function_spawner, method_spawner

# ThreadGroup for managing multiple concurrent operations
async with ThreadGroup() as group:
    # Add functions to run concurrently
    group.spawn(some_function, arg1, arg2)
    group.spawn(another_function, arg3)

    # Wait for all to complete
    results = await group.gather()

# Function spawner for reusable concurrent execution
spawner = function_spawner(my_function, max_workers=10)
results = await spawner([arg1, arg2, arg3, arg4])

# Method spawner for object methods
obj_spawner = method_spawner(my_object.method, max_workers=5)
results = await obj_spawner([data1, data2, data3])

Testing Utilities

Tools for testing and development:

from anyenv import open_in_playground

# Open interactive playground for testing (where supported)
await open_in_playground(locals())

Environment Compatibility

All functionality automatically adapts to the execution environment:

  • PyOdide: Uses browser-compatible implementations (HTTP through fetch)
  • Standard Python: HTTP through httpx2 (or legacy httpx)
  • Limited environments: Falls back to stdlib implementations
  • Async contexts: Provides async implementations
  • Sync contexts: Provides synchronous alternatives

This ensures your code works consistently across web browsers, Jupyter notebooks, serverless functions, and traditional Python environments.

Metadata

Release files for anyenv 3.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for anyenv 3.1.0
File Size Uploaded Provenance Actions
anyenv-3.1.0.tar.gz 117.1 kB With provenance Details for anyenv-3.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for anyenv 3.1.0
File Interpreter ABI Platform Actions
anyenv-3.1.0-py3-none-any.whl Python 3 none any Details for anyenv-3.1.0-py3-none-any.whl

Total release size: 283.5 kB

Release files / anyenv-3.1.0.tar.gz

Download URL anyenv-3.1.0.tar.gz
Size 117.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6e2ed14658959b00c9b7f408d1d3ec011df62c658408b2b879ce95ef4a491156
BLAKE2b-256 checksum
How to use checksums
9c4690672f53e181c15927b3680896aaec308b30af757ee13ce078ea8b8f7201
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / anyenv-3.1.0-py3-none-any.whl

Download URL anyenv-3.1.0-py3-none-any.whl
Size 166.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
faabce67e6d909e794d8257c0877bd3e5897c85a04f426cfc6dfd5026ba721a5
BLAKE2b-256 checksum
How to use checksums
826a05161e60f7839599c42ff1dfd1fb99d9292894672937c7720fec0b6f7931
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for anyenv 3.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for anyenv-3.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page