Telepath
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
- breaking Version 0.3.1 dropped support for Python versions older than 3.8 and Django versions older than 3.2. Projects on older environments must either upgrade Python/Django or pin telepath to an earlier version.
- gotcha Telepath handles packing Python objects into primitive types. For client-side unpacking, you must include the `telepath-unpack.js` library in your frontend assets.
- gotcha The `JSContext` object generated on the Python side contains crucial information for the frontend to correctly re-construct your Python objects. Its script tag (`context.as_script_tag()`) must be rendered into your HTML.
- deprecated While older manual packing methods might still function, Telepath v0.2 and v0.3 introduced and refined an API allowing classes to define their own packing logic (via the `Adapter` class and `pack` method). The recommended approach is to use this dedicated adapter pattern.
Install
-
pip install telepath
Imports
- Adapter
from telepath import Adapter
- register
from telepath import register
- JSContext
from telepath import JSContext
- pack
from telepath import pack
Quickstart
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!'")