> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/feature-management-experimentation/new-to-fme/sdks-and-customer-deployed-components/server-side-configs-sdks/python-sdk.md). Agents can also search and read this documentation through its [MCP server](https://developer.harness.io/~gitbook/mcp).

# Python Configs SDK

Use the Harness FME Python Configs SDK to serve standalone, versioned configuration objects in Python applications.

This guide provides detailed information about our Python Configs SDK. The SDK serves Configs: standalone, versioned configuration objects that you manage independently from feature flags. Configs can be evaluated with or without targeting rules and are well suited for use cases such as AI prompts, model parameters, and other application configuration that benefits from governed, versioned management. Go to our [Python Configs SDK GitHub repository](https://github.com/splitio/python-configs-client) to learn more.

### Before you begin <a href="#before-you-begin" id="before-you-begin"></a>

The Python Configs SDK supports Python 3 (3.7.16 or later).

### Initialization <a href="#initialization" id="initialization"></a>

Set up the Python Configs SDK in your code base with two simple steps.

#### 1. Import the SDK into your project <a href="#id-1-import-the-sdk-into-your-project" id="id-1-import-the-sdk-into-your-project"></a>

The SDK is published using `pip`, so it is fully integrated with your workflow.

{% code title="pip" %}

```bash
pip install splitio_configs==1.0.0b2
```

{% endcode %}

#### 2. Instantiate the SDK and create a new client <a href="#id-2-instantiate-the-sdk-and-create-a-new-client" id="id-2-instantiate-the-sdk-and-create-a-new-client"></a>

{% tabs %}
{% tab title="Multi-threaded" %}

```python
from splitio_configs import ConfigsClient, TimeoutException

client = ConfigsClient('YOUR_SDK_KEY')
try:
    client.block_until_ready()
except TimeoutException:
    # SDK_READY_TIMED_OUT: evaluations will return the fallback config or a Config with variant "control".
    pass
```

{% endtab %}

{% tab title="asyncio" %}

```python
import asyncio
from splitio_configs import ConfigsClientAsync, TimeoutException

async def main():
    client = ConfigsClientAsync('YOUR_SDK_KEY')
    try:
        await client.block_until_ready()
    except TimeoutException:
        # SDK_READY_TIMED_OUT: evaluations will return the fallback config or a Config with variant "control".
        pass

asyncio.run(main())
```

{% endtab %}
{% endtabs %}

We recommend instantiating the client once as a singleton and reusing it throughout your application.

Configure the SDK with the SDK key for the FME environment that you would like to access. Go to [API keys](https://developer.harness.io/feature-management-experimentation/management-and-administration/api-keys.md) to learn how to retrieve a server-side SDK key.

### Use the SDK <a href="#use-the-sdk" id="use-the-sdk"></a>

#### Basic use <a href="#basic-use" id="basic-use"></a>

When the SDK is instantiated, it kicks off background jobs to update an in-memory cache with config definitions fetched from Harness servers. While the SDK is in this intermediate state, if it is asked to evaluate a config, it does not fail. Instead, it returns a fallback config or, if no fallback is configured, a `Config` with `variant` equal to `"control"` and an empty `value` (`{}`).

To make sure the SDK has loaded the latest definitions before evaluating, wait for the SDK to be ready before calling `get_config`.

The `get_config` method returns a `Config` object with two properties:

* **`variant`:** The string name of the resolved variant.
* **`value`:** The raw JSON object (Python dict) associated with that variant.

If you do not pass a target, the SDK returns the default variant of the config. If you pass a target, the SDK evaluates the config's targeting rules against that target.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
from splitio_configs import ConfigsClient, Target, TimeoutException

client = ConfigsClient('YOUR_SDK_KEY')
try:
    client.block_until_ready()
except TimeoutException:
    # Evaluations will return the fallback config or a Config with variant "control".
    pass

# Without target: returns the default variant of the config
default_config = client.get_config('CONFIG_NAME')
print(default_config.variant)  # example: 'v1'
print(default_config.value)    # example: {'prompt': 'Hello world', 'temperature': 0.5}

# With target: evaluates targeting rules for the given key
target = Target('user-123')
config = client.get_config('CONFIG_NAME', target)
print(config.variant, config.value)
```

{% endtab %}

{% tab title="asyncio" %}

```python
import asyncio
from splitio_configs import ConfigsClientAsync, Target, TimeoutException

async def main():
    client = ConfigsClientAsync('YOUR_SDK_KEY')
    try:
        await client.block_until_ready()
    except TimeoutException:
        # Evaluations will return the fallback config or a Config with variant "control".
        pass

    # Without target: returns the default variant of the config
    default_config = await client.get_config('CONFIG_NAME')
    print(default_config.variant)  # 'v1'
    print(default_config.value)    # {'prompt': 'Hello world', 'temperature': 0.5}

    # With target: evaluates targeting rules for the given key
    target = Target('user-123')
    config = await client.get_config('CONFIG_NAME', target)
    print(config.variant, config.value)

asyncio.run(main())
```

{% endtab %}
{% endtabs %}

If a config cannot be evaluated, the SDK returns the fallback config value: default `Config` with `variant` `"control"` and empty object `value`, unless overridden globally or per config. Go to [Configure fallback configs](#configure-fallback-configs) to learn more.

#### Attribute syntax <a href="#attribute-syntax" id="attribute-syntax"></a>

To [target based on custom attributes](https://developer.harness.io/feature-management-experimentation/use-fme/feature-management/targeting/target-with-custom-attributes.md), pass a `Target` object with a `key` and an `attributes` dictionary to the `get_config` method.

In the example below, we evaluate a config for a user. The provided attributes `plan_type`, `registered_date`, `permissions`, `paying_customer`, and `deal_size` are passed to the `get_config` call. These attributes are compared and evaluated against the targeting rules defined for the config in Harness FME to decide which variant to resolve.

The supported attribute types are: strings, numbers, dates, booleans, and sets. The proper data type and syntax for each are:

* **Strings:** Use type String.
* **Numbers:** Use type Integer or Float.
* **Dates:** Express the value as the number of `seconds since epoch` in UTC.
* **Booleans:** Use type Boolean.
* **Sets:** Use type List.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
import arrow
from splitio_configs import ConfigsClient, Target, TimeoutException

target = Target('user-123', attributes={
    # date attributes are handled as seconds since epoch
    'registered_date': arrow.utcnow().timestamp(),
    # this string will be compared against a list called plan_type
    'plan_type': 'growth',
    # this number will be compared against a const value called deal_size
    'deal_size': 10000,
    # this boolean will be compared against a const value called paying_customer
    'paying_customer': True,
    # this list will be compared against a set called permissions
    'permissions': ['read', 'write']
})
config = client.get_config('CONFIG_NAME', target)
print(config.variant, config.value)
```

{% endtab %}

{% tab title="asyncio" %}

```python
import arrow
from splitio_configs import ConfigsClientAsync, Target, TimeoutException

target = Target('user-123', attributes={
    'registered_date': arrow.utcnow().timestamp(),
    'plan_type': 'growth',
    'deal_size': 10000,
    'paying_customer': True,
    'permissions': ['read', 'write']
})
config = await client.get_config('CONFIG_NAME', target)
print(config.variant, config.value)
```

{% endtab %}
{% endtabs %}

#### Append properties to impressions <a href="#append-properties-to-impressions" id="append-properties-to-impressions"></a>

[Impressions](https://developer.harness.io/feature-management-experimentation/use-fme/feature-management/monitoring-and-analysis/impressions.md) are generated by the SDK each time a `get_config` method is called with a target. These impressions are periodically sent back to Harness servers for feature monitoring and experimentation.

You can append properties to an impression by passing an `EvaluationOptions` object to the `get_config` method. These properties are then included in the impression sent by the SDK and can provide useful context to the impression data.

Three types of properties are supported: strings, numbers, and booleans.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
from splitio_configs import ConfigsClient, Target, TimeoutException, EvaluationOptions

target = Target('user-123')
evaluation_options = EvaluationOptions(properties={'package': 'premium', 'admin': True, 'discount': 50})
config = client.get_config('CONFIG_NAME', target, evaluation_options)
```

{% endtab %}

{% tab title="asyncio" %}

```python
from splitio_configs import ConfigsClientAsync, Target, TimeoutException, EvaluationOptions

target = Target('user-123')
evaluation_options = EvaluationOptions(properties={'package': 'premium', 'admin': True, 'discount': 50})
config = await client.get_config('CONFIG_NAME', target, evaluation_options)
```

{% endtab %}
{% endtabs %}

#### Shutdown <a href="#shutdown" id="shutdown"></a>

Call the `destroy()` method before letting a process using the SDK exit, as this method gracefully shuts down the SDK by stopping all background sync jobs, clearing caches, closing connections, and flushing any remaining unpublished events and impressions.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
import threading

stop_event = threading.Event()
client.destroy(stop_event)
stop_event.wait()
```

{% endtab %}

{% tab title="asyncio" %}

```python
await client.destroy()
```

{% endtab %}
{% endtabs %}

After `destroy()` is called and finishes, any subsequent invocations to `get_config` return the fallback config or, if no fallback is configured, a `Config` with `variant` `"control"` and empty object `value`.

### Track <a href="#track" id="track"></a>

Use the `track` method to record any actions your customers perform. Each action is known as an `event` and corresponds to an `event type`. Calling `track` through one of our SDKs or via the API allows you to measure the impact of your configs on your users' actions and metrics.

Go to [Events](https://developer.harness.io/feature-management-experimentation/use-fme/release-monitoring/events.md) to learn more about using track events in features.

In the examples below, you can see that the `track` method can take up to five arguments. The proper data type and syntax for each are:

* **key:** The key that identifies the entity related to this event. The expected data type is **String**.
* **TRAFFIC\_TYPE:** The traffic type of the key in the track call. The expected data type is **String**. Go to [traffic types](https://developer.harness.io/feature-management-experimentation/management-and-administration/traffic-types.md) to learn more.
* **EVENT\_TYPE:** The event type that this event should correspond to. The expected data type is **String**. Full requirements on this argument are:
  * Contains 63 characters or fewer.
  * Starts with a letter or number.
  * Contains only letters, numbers, hyphen, underscore, or period.
  * This is the regular expression we use to validate the value: `[a-zA-Z0-9][-_\.a-zA-Z0-9]{0,62}`
* **VALUE:** (Optional) The value to be used in creating the metric. This field can be sent as None or 0 if you intend to purely use the count function when creating a metric. The expected data type is **Integer** or **Float**.
* **PROPERTIES:** (Optional) An object of key-value pairs that can be used to filter your metrics. Go to [Event properties](https://developer.harness.io/feature-management-experimentation/use-fme/release-monitoring/events.md#event-properties) to learn more. FME currently supports three types of properties: strings, numbers, and booleans.

The `track` method returns a boolean value of `True` or `False` to indicate whether the SDK was able to successfully queue the event to be sent back to Harness servers on the next event post. The SDK returns `False` if an incorrect input has been provided.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
# If you would like to send an event without a value
queued = client.track('key', 'TRAFFIC_TYPE', 'EVENT_TYPE')

# Example
queued = client.track('john@doe.com', 'user', 'page_load_time')

# If you would like to associate a value with an event
queued = client.track('key', 'TRAFFIC_TYPE', 'EVENT_TYPE', 83.334)

# Example
queued = client.track('john@doe.com', 'user', 'page_load_time', 83.334)

# If you would like to associate a value and properties with an event
properties = {'package': 'premium', 'admin': True, 'discount': 50}
queued = client.track('john@doe.com', 'user', 'page_load_time', 83.334, properties)

# If you would like to associate only properties with an event
queued = client.track('john@doe.com', 'user', 'page_load_time', None, properties)
```

{% endtab %}

{% tab title="asyncio" %}

```python
# If you would like to send an event without a value
queued = await client.track('key', 'TRAFFIC_TYPE', 'EVENT_TYPE')

# Example
queued = await client.track('john@doe.com', 'user', 'page_load_time')

# If you would like to associate a value with an event
queued = await client.track('key', 'TRAFFIC_TYPE', 'EVENT_TYPE', 83.334)

# Example
queued = await client.track('john@doe.com', 'user', 'page_load_time', 83.334)

# If you would like to associate a value and properties with an event
properties = {'package': 'premium', 'admin': True, 'discount': 50}
queued = await client.track('john@doe.com', 'user', 'page_load_time', 83.334, properties)

# If you would like to associate only properties with an event
queued = await client.track('john@doe.com', 'user', 'page_load_time', None, properties)
```

{% endtab %}
{% endtabs %}

### Configuration <a href="#configuration" id="configuration"></a>

The SDK has a number of knobs for configuring performance. Each knob is tuned to a reasonable default. However, you can override the value while instantiating the SDK. The parameters available for configuration are shown below.

| **Configuration**   | **Description**                                                                                                                                                             | **Default value** |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
| `polling_rate`      | How often, in seconds, the SDK polls for config and segment updates. Minimum value: `5`.                                                                                    | `60`              |
| `push_rate`         | How often, in seconds, the SDK flushes queued events and impressions. Minimum value: `60`.                                                                                  | `60`              |
| `queue_size`        | Maximum number of events or impressions queued in memory before a forced flush. Minimum value: `1000`.                                                                      | `10000`           |
| `ready_timeout`     | Time in seconds before the SDK raises a `TimeoutException` during `block_until_ready`. Use `-1` to disable the timeout.                                                     | `10`              |
| `fallback_configs`  | Fallback configs returned when evaluation fails or the requested config name does not exist. Go to [Configure fallback configs](#configure-fallback-configs) to learn more. | `None`            |
| `service_endpoints` | Allows Override of the base URLs for config client services.                                                                                                                | see table below   |

**ServiceEndpoints parameters**

| **Configuration** | **Description**                                                                    | **Default value**            |
| ----------------- | ---------------------------------------------------------------------------------- | ---------------------------- |
| `configs`         | Override the base URL for config and segment requests (constructor parameter).     | `'https://configs.split.io'` |
| `events`          | Override the base URL for events and impressions requests (constructor parameter). | `'https://events.split.io'`  |
| `auth`            | Override the base URL for JWT authentication requests (constructor parameter).     | `'https://auth.split.io'`    |

To set each of the parameters defined above, use the following syntax.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
from splitio_configs import ConfigsClient, ConfigsClientSettings, ServiceEndpoints

endpoints = ServiceEndpoints(
    configs='https://configs.split.io',
    events='https://events.split.io',
    auth='https://auth.split.io'
)

settings = ConfigsClientSettings(
    polling_rate=60,
    push_rate=60,
    queue_size=10000,
    ready_timeout=10,
    service_endpoints=endpoints
)

client = ConfigsClient('YOUR_SDK_KEY', settings)
```

{% endtab %}

{% tab title="asyncio" %}

```python
from splitio_configs import ConfigsClientAsync, ConfigsClientSettings, ServiceEndpoints

async def main():
    endpoints = ServiceEndpoints(
        configs='https://configs.split.io',
        events='https://events.split.io',
        auth='https://auth.split.io'
    )

    settings = ConfigsClientSettings(
        polling_rate=60,
        push_rate=60,
        queue_size=10000,
        ready_timeout=10,
        service_endpoints=endpoints
    )

    client = ConfigsClientAsync('YOUR_SDK_KEY', settings)

asyncio.run(main())
```

{% endtab %}
{% endtabs %}

#### Configure fallback configs <a href="#configure-fallback-configs" id="configure-fallback-configs"></a>

Fallback configs let you define a `Config` value to be returned when a config cannot be evaluated. By default, the SDK returns a `Config` with `variant` `"control"` and an empty `value` (`{}`), but you can override this globally or for individual configs at the SDK level.

This is useful when you want to:

* Maintain a predictable user experience during outages or evaluation failures.
* Protect critical user flows by returning a safe, stable configuration.
* Customize behavior per config so each evaluation inherits appropriate safe defaults if something goes wrong.

Each fallback entry must include a `variant` (string) and a `value` (dict) matching the [Config return type](#use-the-sdk).

**Global fallback config**

Set a global fallback config when instantiating the SDK. This value is returned whenever any config cannot be evaluated.

```python
from splitio_configs import ConfigsClient, ConfigsClientSettings, FallbackConfigs, Config

client = ConfigsClient(
    'YOUR_SDK_KEY',
    config_client_settings = ConfigsClientSettings(
        fallback_configs = FallbackConfigs(
            global_fallback = Config("v1", {'prompt': 'default prompt', 'temperature': 0.9})
        )
    )
)
```

**Per-config fallback**

You can also set a fallback config per config name via the `by_name_fallback` sub-option. Per-config fallbacks always take precedence over the global fallback, so if both are defined, the SDK returns the per-config value when that config cannot be evaluated.

```python
from splitio_configs import ConfigsClient, ConfigsClientSettings, FallbackConfigs, Config

client = ConfigsClient(
    'YOUR_SDK_KEY',
    config_client_settings = ConfigsClientSettings(
        fallback_configs = FallbackConfigs(
            by_name_fallback = {
                'chat_bot_config': Config("v2", {'prompt': 'fallback chat prompt', 'temperature': 0.1})
            }
        )
    )
)
```

### Advanced use cases <a href="#advanced-use-cases" id="advanced-use-cases"></a>

This section describes advanced use cases and features provided by the SDK.

#### Subscribe to events <a href="#subscribe-to-events" id="subscribe-to-events"></a>

You can listen for three different events from the SDK.

* `SDK_READY`. This event fires once the SDK is ready to evaluate configs using the most up-to-date version of your rollout plan, downloaded from Harness servers.
* `SDK_READY_TIMED_OUT`. This event fires if the SDK could not fully download the data from Harness servers (`SDK_READY` event) within the time specified by the `ready_timeout` setting. This event does not indicate that the SDK initialization was interrupted. The SDK continues downloading and fires the `SDK_READY` event when finished. This delayed `SDK_READY` event may happen with slow connections or large rollout plans with many configs and segments.
* `SDK_UPDATE`. This event fires whenever your rollout plan is changed. Listen for this event to refresh your app whenever a config or segment is changed in Harness FME.

These events provide hooks to run custom logic whenever the SDK state changes.

{% tabs %}
{% tab title="Multi-threaded" %}

```python
from splitio_configs import SdkEvent

def ready_callback(metadata):
    print("SDK is ready.")

def ready_timed_out_callback():
    print("SDK emitted SDK_READY_TIMED_OUT event.")

def update_callback(metadata):
    print(metadata.get_type())   # 'CONFIGS_UPDATE' or 'SEGMENTS_UPDATE'
    print(metadata.get_names())  # set of impacted config names; empty for segment-only updates

client.on(SdkEvent.SDK_READY, ready_callback)
client.on(SdkEvent.SDK_READY_TIMED_OUT, ready_timed_out_callback)
client.on(SdkEvent.SDK_UPDATE, update_callback)
```

{% endtab %}

{% tab title="asyncio" %}

```python
from splitio_configs import SdkEvent

async def ready_callback(metadata):
    print("SDK is ready.")

async def update_callback(metadata):
    print(metadata.get_type())   # 'CONFIGS_UPDATE' or 'SEGMENTS_UPDATE'
    print(metadata.get_names())  # set of impacted config names; empty for segment-only updates

await client.on(SdkEvent.SDK_READY, ready_callback)
await client.on(SdkEvent.SDK_UPDATE, update_callback)
```

{% endtab %}
{% endtabs %}

**Include metadata**

`metadata` provides additional context for events:

* `SDK_UPDATE`: Includes `get_type()` (`CONFIGS_UPDATE` or `SEGMENTS_UPDATE`) and `get_names()` (set of impacted config names; empty for segment-only updates).
* `SDK_READY` and `SDK_READY_TIMED_OUT`: No metadata is included.

#### Logging <a href="#logging" id="logging"></a>

The SDK uses Python's standard `logging` module. The root logger name is `splitio_configs`. You can configure logging level and handlers as needed.

```python
import logging

logger = logging.getLogger('splitio_configs')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.WARNING)
```

{% @harness-feedback/feedback %}
