Telepath

0.3.1 · active · verified Thu Apr 09

Telepath is a Python library designed for exchanging data between Python and JavaScript. It enables Python objects to be packed into primitive types suitable for frontend consumption, typically within a web context. The current version is 0.3.1. Releases are infrequent, usually tied to specific feature additions or compatibility updates, particularly concerning Django versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a custom Python object, create a Telepath adapter for it, register the adapter, and then pack an instance of the object into a JavaScript-compatible format. It also shows how to generate the necessary JavaScript context for the frontend to unpack the data using the companion `telepath-unpack.js` library.

from telepath import Adapter, register, JSContext, pack

# 1. Define a custom Python object
class MyCustomObject:
    def __init__(self, message, value):
        self.message = message
        self.value = value

# 2. Define a Telepath adapter for your custom object
class MyCustomObjectAdapter(Adapter):
    js_constructor = 'telepath.MyCustomObject'

    def pack(self, obj, context):
        # Pack the Python object into a list of primitive types
        return [obj.message, obj.value]

# 3. Register the adapter with the custom object
register(MyCustomObject, MyCustomObjectAdapter)

# 4. Create an instance of your custom object
my_instance = MyCustomObject("Hello from Python!", 123)

# 5. Create a JSContext and pack the object
context = JSContext()
packed_data = pack(my_instance, context)

print("--- Python Side ---")
print(f"Original object: {my_instance.message}, {my_instance.value}")
print(f"Packed data: {packed_data}")

# The context provides the necessary JavaScript to unpack the data on the frontend.
# This script tag should be included in your HTML.
print("\n--- Frontend Integration (JavaScript) ---")
print("Include this script tag in your HTML header:")
print(context.as_script_tag())

print("\nOn the frontend, with telepath-unpack.js loaded, you would then do:")
print("// const myUnpackedObject = window.telepath.unpack(packed_data);")
print("// console.log(myUnpackedObject.message); // 'Hello from Python!'")

view raw JSON →