Skip to content

Python SDK Guide

This guide covers adding Liteguard to a Python application.


Prerequisites

  • A Project Client Token from your Liteguard project. Follow the Getting Started guide through the Copy a Project Client Token step if you do not have one yet.
  • Python 3.9 or later.

Install the SDK

bash
pip install liteguard

Initialize the client

Create a single LiteguardClient instance and call start() during application startup.

python
from liteguard import LiteguardClient
import os

client = LiteguardClient(os.environ["LITEGUARD_TOKEN"])
client.start()

start() fetches the initial bundle and launches background threads for periodic refresh and telemetry flush. It is a synchronous blocking call that returns once the initial fetch completes.

Do not commit your token to source control. Read it from an environment variable or secrets manager.

Environment

python
client = LiteguardClient(
    os.environ["LITEGUARD_TOKEN"],
    environment=os.environ.get("LITEGUARD_ENV", "default"),
)

The slug must match one of the environments defined in your workspace. Slugs are visible in Config > Workspace > [your workspace] under Environments.


Evaluate a guard

client.is_open(guard_name) is synchronous and reads from the locally cached bundle. No network call occurs per check.

python
if client.is_open("payments.checkout"):
    # guarded code path

Passing properties

Pass a properties dict to match against rules configured in the Liteguard UI:

python
if client.is_open("payments.checkout", properties={
    "user_id": request.user.id,
    "plan": request.user.plan,
}):
    # guarded code path

Scopes

Create a LiteguardScope once per request with the caller's properties and reuse it for multiple guard checks:

python
scope = client.create_scope(
    user_id=request.user.id,
    plan=request.user.plan,
)

if scope.is_open("payments.checkout"):
    pass

if scope.is_open("billing.invoice_download"):
    pass

Scopes are immutable. Derive variants with scope.with_properties(...) or scope.add_properties(...).

Context propagation

The Python SDK uses contextvars.ContextVar for scope propagation. You can attach a scope at the request boundary and have downstream calls pick it up automatically:

python
# In middleware or a context manager:
with client.run_with_scope(scope):
    handle_request()

# Downstream:
client.is_open("feature.x")  # uses the scope from the enclosing context

Shut down cleanly

Flush buffered telemetry before process exit:

python
import atexit
atexit.register(client.shutdown)

Or call it explicitly:

python
client.shutdown()

shutdown() flushes pending signals and stops the background threads.


Verify in Liteguard

After calling is_open at least once, open the Guards tab and confirm your guard appears. See Your First Guard to configure its behavior.


Next steps