Skip to main content

Run async functions seamlessly from sync code using a persistent background event loop.

Project description

palitra

A lightweight bridge between synchronous and asynchronous Python code, maintaining a persistent event loop in a background thread. It allows you to call async def functions directly from regular (sync) code without blocking or complex event loop reentry.

Unlike asyncio.run(), which creates and tears down a new event loop on each call, using palitra.run() eliminates that overhead — preserving async state and resources (like aiohttp sessions or database connections) across multiple calls.

a.k.a. "palette" — captures the essence of the library: blending differently colored (sync/async) functions like on an artist’s palette.

⚠️ Known issues: unexpected behaivour in 3.13t build.

If something breaks in your environment, please report an issue — the whole purpose of this library is to spare developers from reinventing async/sync bridges in every project. Your feedback directly helps improve its reliability and real-world compatibility.

Inspired by Running async code from sync in Python asyncio by lemon24 and related discussions such as Celery #9058.

Features

  • ✅ Runs a persistent asyncio event loop in a background thread
  • ✅ Simple, thread-safe API for running coroutines from sync code
  • ✅ No monkey patching or global loop overrides
  • ✅ Automatic cleanup via atexit and weakref to global runner (if used)
  • ✅ Lightweight: no external dependencies

Documentation

Why this even exists?

Usage Examples

This is not ideal, but in real-world scenarios, migrating to ASGI isn’t always possible. When stuck with WSGI, palitra lets you still use async features to get things working.

Flask with aiohttp

from flask import Flask, jsonify
import palitra
import aiohttp
import asyncio

app = Flask(__name__)

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.json()

@app.route('/api/comments')
def get_comments():
    async def fetch_all():
        async with aiohttp.ClientSession() as session:
            urls = [
                'https://jsonplaceholder.typicode.com/comments/1',
                'https://jsonplaceholder.typicode.com/comments/2',
                'https://jsonplaceholder.typicode.com/comments/3',
            ]
            return await asyncio.gather(*[fetch_url(session, url) for url in urls])

    comments = palitra.run(fetch_all())
    return jsonify(comments)

if __name__ == '__main__':
    app.run()

Celery

import palitra
from celery import Celery
import asyncio
import time

celery_app = Celery('tasks', broker='pyamqp://guest@localhost//')

async def async_processing(data: str) -> dict:
    await asyncio.sleep(0.5)  # simulate async I/O
    return {"input": data, "processed": True, "timestamp": time.time()}

@celery_app.task(name="process_async")
def sync_celery_wrapper(data: str):
    return palitra.run(async_processing(data))

Contributing

Pull requests are welcome! Please:

  • Document known issues or caveats
  • Include test coverage for new features
  • Keep the code as simple and minimal as possible
  • Prefer clarity over cleverness

Things that need more work:

  • Proper stress testing
  • Verifying thread safety in edge cases
  • Detecting and eliminating memory leaks
  • Ensuring reliable shutdown under all conditions

License

BSD-3-Clause

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

palitra-0.0.1.tar.gz (7.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

palitra-0.0.1-py3-none-any.whl (7.7 kB view details)

Uploaded Python 3

File details

Details for the file palitra-0.0.1.tar.gz.

File metadata

  • Download URL: palitra-0.0.1.tar.gz
  • Upload date:
  • Size: 7.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for palitra-0.0.1.tar.gz
Algorithm Hash digest
SHA256 6421656a5af6f6a6c41de7afd6fa67d168337e136292d0f2a0ba880c671c5595
MD5 dc89f2d3ce5f778d0e8653ffe63303aa
BLAKE2b-256 97ccde94fab9f59f991b417bb5929a575d2abce7a60e910e976f59eaa045cdc0

See more details on using hashes here.

Provenance

The following attestation bundles were made for palitra-0.0.1.tar.gz:

Publisher: ci.yml on abebus/palitra

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file palitra-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: palitra-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 7.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for palitra-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 76c6b4cc7061eb3a3d6325779f9e6b040d24f475515868dd010416ed06937b61
MD5 3e42eb1513b55313e6098dc6bcf40ce8
BLAKE2b-256 a64f78642f9645316e0a5d973080844bc1026f1ae194f2793131a25c69933be5

See more details on using hashes here.

Provenance

The following attestation bundles were made for palitra-0.0.1-py3-none-any.whl:

Publisher: ci.yml on abebus/palitra

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page