Core API

ldclient module

The ldclient module contains the most common top-level entry points for the SDK.

class ldclient.Context(kind: str | None, key: str, name: str | None = None, anonymous: bool = False, attributes: dict | None = None, private_attributes: list[str] | None = None, multi_contexts: list[ldclient.context.Context] | None = None, allow_empty_key: bool = False, error: str | None = None)[source]

A collection of attributes that can be referenced in flag evaluations and analytics events. This entity is also called an “evaluation context.”

To create a Context of a single kind, such as a user, you may use create() when only the key and the kind are relevant; or, to specify other attributes, use builder().

To create a Context with multiple kinds (a multi-context), use create_multi() or multi_builder().

A Context can be in an error state if it was built with invalid attributes. See valid and error.

A Context is immutable once created.

DEFAULT_KIND = 'user'

A constant for the default context kind of “user”.

MULTI_KIND = 'multi'

A constant for the kind that all multi-contexts have.

property anonymous: bool

Returns True if this context is only intended for flag evaluations and will not be indexed by LaunchDarkly.

The default value is False. False means that this Context represents an entity such as a user that you want to be able to see on the LaunchDarkly dashboard.

Setting anonymous to True excludes this context from the database that is used by the dashboard. It does not exclude it from analytics event data, so it is not the same as making attributes private; all non-private attributes will still be included in events and data export. There is no limitation on what other attributes may be included (so, for instance, anonymous does not mean there is no name), and the context will still have whatever key you have given it.

This value is also addressable in evaluations as the attribute name “anonymous”. It is always treated as a boolean true or false in evaluations.

See:

ldclient.ContextBuilder.anonymous()

classmethod builder(key: str) ContextBuilder[source]

Creates a builder for building a Context.

You may use ldclient.ContextBuilder methods to set additional attributes and/or change the context kind before calling ldclient.ContextBuilder.build(). If you do not change any values, the defaults for the Context are that its kind is DEFAULT_KIND, its key is set to the key parameter specified here, anonymous is False, and it has no values for any other attributes.

This method is for building a Context that has only a single kind. To define a multi-context, use create_multi() or multi_builder().

Parameters:

key – the context key

Returns:

a new builder

See:

create()

See:

create_multi()

classmethod builder_from_context(context: Context) ContextBuilder[source]

Creates a builder whose properties are the same as an existing single-kind Context.

You may then change the builder’s state in any way and call ldclient.ContextBuilder.build() to create a new independent Context.

Parameters:

context – the context to copy from

Returns:

a new builder

classmethod create(key: str, kind: str | None = None) Context[source]

Creates a single-kind Context with only the key and the kind specified.

If you omit the kind, it defaults to “user” (DEFAULT_KIND).

Parameters:
  • key – the context key

  • kind – the context kind; if omitted, it is DEFAULT_KIND (“user”)

Returns:

a context

See:

builder()

See:

create_multi()

classmethod create_multi(*contexts: Context) Context[source]

Creates a multi-context out of the specified single-kind Contexts.

To create a Context for a single context kind, use create() or builder().

You may use multi_builder() instead if you want to add contexts one at a time using a builder pattern.

For the returned Context to be valid, the contexts list must not be empty, and all of its elements must be valid Contexts. Otherwise, the returned Context will be invalid as reported by error().

If only one context parameter is given, the method returns that same context.

If a nested context is a multi-context, this is exactly equivalent to adding each of the individual kinds from it separately. See ldclient.ContextMultiBuilder.add().

Parameters:

contexts – the individual contexts

Returns:

a multi-context

See:

create()

See:

multi_builder()

property custom_attributes: Iterable[str]

Gets the names of all non-built-in attributes that have been set in this context.

For a single-kind context, this includes all the names that were passed to ldclient.ContextBuilder.set() as long as the values were not None (since a value of None in LaunchDarkly is equivalent to the attribute not being set).

For a multi-context, there are no such names.

Returns:

an iterable

property error: str | None

Returns None for a valid Context, or an error message for an invalid one.

If this is None, then valid is True. If it is not None, then valid is False.

classmethod from_dict(props: dict) Context[source]

Creates a Context from properties in a dictionary, corresponding to the JSON representation of a context.

Parameters:

props – the context properties

Returns:

a context

property fully_qualified_key: str

A string that describes the Context uniquely based on kind and key values.

This value is used whenever LaunchDarkly needs a string identifier based on all of the kind and key values in the context. Applications typically do not need to use it.

get(attribute: str) Any[source]

Looks up the value of any attribute of the context by name.

For a single-kind context, the attribute name can be any custom attribute that was set by ldclient.ContextBuilder.set(). It can also be one of the built-in ones like “kind”, “key”, or “name”; in such cases, it is equivalent to kind, key, or name.

For a multi-context, the only supported attribute name is “kind”. Use get_individual_context() to get the context for a particular kind and then get its attributes.

If the value is found, the return value is the attribute value. If there is no such attribute, the return value is None. An attribute that actually exists cannot have a value of None.

Context has a __getitem__ magic method equivalent to get, so context['attr'] behaves the same as context.get('attr').

Parameters:

attribute – the desired attribute name

Returns:

the attribute value, or None if there is no such attribute

See:

ldclient.ContextBuilder.set()

get_individual_context(kind: int | str) Context | None[source]

Returns the single-kind Context corresponding to one of the kinds in this context.

The kind parameter can be either a number representing a zero-based index, or a string representing a context kind.

If this method is called on a single-kind Context, then the only allowable value for kind is either zero or the same value as the Context’s kind, and the return value on success is the same Context.

If the method is called on a multi-context, and kind is a number, it must be a non-negative index that is less than the number of kinds (that is, less than the value of individual_context_count), and the return value on success is one of the individual Contexts within. Or, if kind is a string, it must match the context kind of one of the individual contexts.

If there is no context corresponding to kind, the method returns None.

Parameters:

kind – the index or string value of a context kind

Returns:

the context corresponding to that index or kind, or None

See:

individual_context_count

property individual_context_count: int

Returns the number of context kinds in this context.

For a valid individual context, this returns 1. For a multi-context, it returns the number of context kinds. For an invalid context, it returns zero.

Returns:

the number of context kinds

See:

get_individual_context()

property key: str

Returns the context’s key attribute.

For a single context, this value is set by create(), or ldclient.ContextBuilder.key().

For a multi-context, there is no single value and key returns an empty string. Use get_individual_context() to get the Context for a particular kind, then get the key of that Context.

See:

ldclient.ContextBuilder.key()

See:

create()

property kind: str

Returns the context’s kind attribute.

Every valid context has a non-empty kind. For multi-contexts, this value is MULTI_KIND and the kinds within the context can be inspected with get_individual_context().

See:

ldclient.ContextBuilder.kind()

See:

create()

classmethod multi_builder() ContextMultiBuilder[source]

Creates a builder for building a multi-context.

This method is for building a Context that contains multiple contexts, each for a different context kind. To define a single context, use create() or builder() instead.

The difference between this method and create_multi() is simply that the builder allows you to add contexts one at a time, if that is more convenient for your logic.

Returns:

a new builder

See:

builder()

See:

create_multi()

property multiple: bool

True if this is a multi-context.

If this value is True, then kind is guaranteed to be MULTI_KIND, and you can inspect the individual context for each kind with get_individual_context().

If this value is False, then kind is guaranteed to return a value that is not MULTI_KIND.

See:

create_multi()

property name: str | None

Returns the context’s name attribute.

For a single context, this value is set by ldclient.ContextBuilder.name(). It is None if no value was set.

For a multi-context, there is no single value and name returns None. Use get_individual_context() to get the Context for a particular kind, then get the name of that Context.

See:

ldclient.ContextBuilder.name()

property private_attributes: Iterable[str]

Gets the list of all attribute references marked as private for this specific Context.

This includes all attribute names/paths that were specified with ldclient.ContextBuilder.private().

Returns:

an iterable

to_dict() dict[str, Any][source]

Returns a dictionary of properties corresponding to the JSON representation of the context (as an associative array), in the standard format used by LaunchDarkly SDKs.

Use this method if you are passing context data to the front end for use with the LaunchDarkly JavaScript SDK.

Returns:

a dictionary corresponding to the JSON representation

to_json_string() str[source]

Returns the JSON representation of the context as a string, in the standard format used by LaunchDarkly SDKs.

This is equivalent to calling to_dict() and then json.dumps().

Returns:

the JSON representation as a string

property valid: bool

True for a valid Context, or False for an invalid one.

A valid context is one that can be used in SDK operations. An invalid context is one that is missing necessary attributes or has invalid attributes, indicating an incorrect usage of the SDK API. The only ways for a context to be invalid are:

  • The kind property had a disallowed value. See ldclient.ContextBuilder.kind().

  • For a single context, the key property was None or empty.

  • You tried to create a multi-context without specifying any contexts.

  • You tried to create a multi-context using the same context kind more than once.

  • You tried to create a multi-context where at least one of the individual Contexts was invalid.

In any of these cases, valid will be False, and error will return a description of the error.

Since in normal usage it is easy for applications to be sure they are using context kinds correctly, and because throwing an exception is undesirable in application code that uses LaunchDarkly, the SDK stores the error state in the Context itself and checks for such errors at the time the Context is used, such as in a flag evaluation. At that point, if the context is invalid, the operation will fail in some well-defined way as described in the documentation for that method, and the SDK will generally log a warning as well. But in any situation where you are not sure if you have a valid Context, you can check valid or error.

class ldclient.ContextBuilder(key: str, copy_from: Context | None = None)[source]

A mutable object that uses the builder pattern to specify properties for ldclient.Context.

Use this type if you need to construct a context that has only a single kind. To define a multi-context, use ldclient.Context.create_multi() or ldclient.Context.multi_builder().

Obtain an instance of ContextBuilder by calling ldclient.Context.builder(). Then, call setter methods such as name() or set() to specify any additional attributes. Then, call build() to create the context. ContextBuilder setters return a reference to the same builder, so calls can be chained:

context = Context.builder('user-key')             .name('my-name')             .set('country', 'us')             .build
Parameters:

key – the context key

anonymous(anonymous: bool) ContextBuilder[source]

Sets whether the context is only intended for flag evaluations and should not be indexed by LaunchDarkly.

The default value is False. False means that this Context represents an entity such as a user that you want to be able to see on the LaunchDarkly dashboard.

Setting anonymous to True excludes this context from the database that is used by the dashboard. It does not exclude it from analytics event data, so it is not the same as making attributes private; all non-private attributes will still be included in events and data export. There is no limitation on what other attributes may be included (so, for instance, anonymous does not mean there is no name), and the context will still have whatever key you have given it.

This value is also addressable in evaluations as the attribute name “anonymous”. It is always treated as a boolean true or false in evaluations.

Parameters:

anonymous – true if the context should be excluded from the LaunchDarkly database

Returns:

the builder

See:

ldclient.Context.anonymous

build() Context[source]

Creates a Context from the current builder properties.

The Context is immutable and will not be affected by any subsequent actions on the builder.

It is possible to specify invalid attributes for a ContextBuilder, such as an empty key. Instead of throwing an exception, the ContextBuilder always returns an Context and you can check ldclient.Context.valid or ldclient.Context.error to see if it has an error. See ldclient.Context.valid for more information about invalid conditions. If you pass an invalid Context to an SDK method, the SDK will detect this and will log a description of the error.

Returns:

a new ldclient.Context

key(key: str) ContextBuilder[source]

Sets the context’s key attribute.

Every context has a key, which is always a string. It cannot be an empty string, but there are no other restrictions on its value.

The key attribute can be referenced by flag rules, flag target lists, and segments.

Parameters:

key – the context key

Returns:

the builder

kind(kind: str) ContextBuilder[source]

Sets the context’s kind attribute.

Every context has a kind. Setting it to an empty string or None is equivalent to ldclient.Context.DEFAULT_KIND (“user”). This value is case-sensitive.

The meaning of the context kind is completely up to the application. Validation rules are as follows:

  • It may only contain letters, numbers, and the characters ., _, and -.

  • It cannot equal the literal string “kind”.

  • For a single context, it cannot equal “multi”.

Parameters:

kind – the context kind

Returns:

the builder

name(name: str | None) ContextBuilder[source]

Sets the context’s name attribute.

This attribute is optional. It has the following special rules:

  • Unlike most other attributes, it is always a string if it is specified.

  • The LaunchDarkly dashboard treats this attribute as the preferred display name for contexts.

Parameters:

name – the context name (None to unset the attribute)

Returns:

the builder

private(*attributes: str) ContextBuilder[source]

Designates any number of Context attributes, or properties within them, as private: that is, their values will not be sent to LaunchDarkly.

Each parameter can be either a simple attribute name, or a slash-delimited path referring to a JSON object property within an attribute.

Parameters:

attributes – attribute names or references to mark as private

Returns:

the builder

set(attribute: str, value: Any) ContextBuilder[source]

Sets the value of any attribute for the context.

This includes only attributes that are addressable in evaluations– not metadata such as private(). If attributeName is "private", you will be setting an attribute with that name which you can use in evaluations or to record data for your own purposes, but it will be unrelated to private().

The allowable types for context attributes are equivalent to JSON types: boolean, number, string, array (list), or object (dictionary). For all attribute names that do not have special meaning to LaunchDarkly, you may use any of those types. Values of different JSON types are always treated as different values: for instance, the number 1 is not the same as the string “1”.

The following attribute names have special restrictions on their value types, and any value of an unsupported type will be ignored (leaving the attribute unchanged):

  • "kind", "key": Must be a string. See kind() and key().

  • "name": Must be a string or None. See name().

  • "anonymous": Must be a boolean. See anonymous().

The attribute name "_meta" is not allowed, because it has special meaning in the JSON schema for contexts; any attempt to set an attribute with this name has no effect.

Values that are JSON arrays or objects have special behavior when referenced in flag/segment rules.

A value of None is equivalent to removing any current non-default value of the attribute. Null/None is not a valid attribute value in the LaunchDarkly model; any expressions in feature flags that reference an attribute with a null value will behave as if the attribute did not exist.

Parameters:
  • attribute – the attribute name to set

  • value – the value to set

Returns:

the builder

try_set(attribute: str, value: Any) bool[source]

Same as set(), but returns a boolean indicating whether the attribute was successfully set.

Parameters:
  • attribute – the attribute name to set

  • value – the value to set

Returns:

True if successful; False if the name was invalid or the value was not an allowed type for that attribute

class ldclient.ContextMultiBuilder[source]

A mutable object that uses the builder pattern to specify properties for a multi-context.

Use this builder if you need to construct a ldclient.Context that contains multiple contexts, each for a different context kind. To define a regular context for a single kind, use ldclient.Context.create() or ldclient.Context.builder().

Obtain an instance of ContextMultiBuilder by calling ldclient.Context.multi_builder(); then, call add() to specify the individual context for each kind. The method returns a reference to the same builder, so calls can be chained:

context = Context.multi_builder()             .add(Context.new("my-user-key"))             .add(Context.new("my-org-key", "organization"))             .build
add(context: Context) ContextMultiBuilder[source]

Adds an individual Context for a specific kind to the builer.

It is invalid to add more than one Context for the same kind, or to add an LContext that is itself invalid. This error is detected when you call build().

If the nested context is a multi-context, this is exactly equivalent to adding each of the individual contexts from it separately. For instance, in the following example, multi1 and multi2 end up being exactly the same:

c1 = Context.new("key1", "kind1")
c2 = Context.new("key2", "kind2")
c3 = Context.new("key3", "kind3")

multi1 = Context.multi_builder().add(c1).add(c2).add(c3).build()

c1plus2 = Context.multi_builder.add(c1).add(c2).build()
multi2 = Context.multi_builder().add(c1plus2).add(c3).build()
Parameters:

context – the context to add

Returns:

the builder

build() Context[source]

Creates a Context from the current builder properties.

The Context is immutable and will not be affected by any subsequent actions on the builder.

It is possible for a ContextMultiBuilder to represent an invalid state. Instead of throwing an exception, the ContextMultiBuilder always returns a Context, and you can check ldclient.Context.valid or ldclient.Context.error to see if it has an error. See ldclient.Context.valid for more information about invalid context conditions. If you pass an invalid context to an SDK method, the SDK will detect this and will log a description of the error.

If only one context was added to the builder, this method returns that context rather than a multi-context.

Returns:

a new Context

ldclient.get() LDClient[source]

Returns the shared SDK client instance, using the current global configuration.

To use the SDK as a singleton, first make sure you have called ldclient.set_config() at startup time. Then get() will return the same shared ldclient.client.LDClient instance each time. The client will be initialized if it has not been already.

If you need to create multiple client instances with different configurations, instead of this singleton approach you can call the ldclient.client.LDClient constructor directly instead.

ldclient.set_config(config: Config)[source]

Sets the configuration for the shared SDK client instance.

If this is called prior to ldclient.get(), it stores the configuration that will be used when the client is initialized. If it is called after the client has already been initialized, the client will be re-initialized with the new configuration (this will result in the next call to ldclient.get() returning a new client instance).

Parameters:

config – the client configuration

ldclient.client module

This submodule contains the client class that provides most of the SDK functionality.

class ldclient.client.LDClient(config: Config, start_wait: float = 5)[source]

The LaunchDarkly SDK client object.

Applications should configure the client at startup time and continue to use it throughout the lifetime of the application, rather than creating instances on the fly. The best way to do this is with the singleton methods ldclient.set_config() and ldclient.get(). However, you may also call the constructor directly if you need to maintain multiple instances.

Client instances are thread-safe.

all_flags_state(context: Context, **kwargs) FeatureFlagsState[source]

Returns an object that encapsulates the state of all feature flags for a given context, including the flag values and also metadata that can be used on the front end. See the JavaScript SDK Reference Guide on Bootstrapping.

This method does not send analytics events back to LaunchDarkly.

Parameters:
  • context – the end context requesting the feature flags

  • kwargs – optional parameters affecting how the state is computed - see below

Keyword Arguments:
  • client_side_only (boolean) – set to True to limit it to only flags that are marked for use with the client-side SDK (by default, all flags are included)

  • with_reasons (boolean) – set to True to include evaluation reasons in the state (see variation_detail())

  • details_only_for_tracked_flags (boolean) – set to True to omit any metadata that is normally only used for event generation, such as flag versions and evaluation reasons, unless the flag has event tracking or debugging turned on

Returns:

a FeatureFlagsState object (will never be None; its valid property will be False if the client is offline, has not been initialized, or the context is invalid)

property big_segment_store_status_provider: BigSegmentStoreStatusProvider

Returns an interface for tracking the status of a Big Segment store.

The ldclient.interfaces.BigSegmentStoreStatusProvider has methods for checking whether the Big Segment store is (as far as the SDK knows) currently operational and tracking changes in this status.

close()[source]

Releases all threads and network connections used by the LaunchDarkly client.

Do not attempt to use the client after calling this method.

property data_source_status_provider: DataSourceStatusProvider

Returns an interface for tracking the status of the data source.

The data source is the mechanism that the SDK uses to get feature flag configurations, such as a streaming connection (the default) or poll requests. The ldclient.interfaces.DataSourceStatusProvider has methods for checking whether the data source is (as far as the SDK knows) currently operational and tracking changes in this status.

Returns:

The data source status provider

property data_store_status_provider: DataStoreStatusProvider

Returns an interface for tracking the status of a persistent data store.

The provider has methods for checking whether the data store is (as far as the SDK knows) currently operational, tracking changes in this status, and getting cache statistics. These are only relevant for a persistent data store; if you are using an in-memory data store, then this method will return a stub object that provides no information.

Returns:

The data store status provider

property flag_tracker: FlagTracker

Returns an interface for tracking changes in feature flag configurations.

The ldclient.interfaces.FlagTracker contains methods for requesting notifications about feature flag changes using an event listener model.

flush()[source]

Flushes all pending analytics events.

Normally, batches of events are delivered in the background at intervals determined by the flush_interval property of ldclient.config.Config. Calling flush() schedules the next event delivery to be as soon as possible; however, the delivery still happens asynchronously on a worker thread, so this method will return immediately.

get_sdk_key() str | None[source]

Returns the configured SDK key.

identify(context: Context)[source]

Reports details about an evaluation context.

This method simply creates an analytics event containing the context properties, to that LaunchDarkly will know about that context if it does not already.

Evaluating a flag, by calling variation() or variation_detail(), also sends the context information to LaunchDarkly (if events are enabled), so you only need to use identify() if you want to identify the context without evaluating a flag.

Parameters:

context – the context to register

is_initialized() bool[source]

Returns true if the client has successfully connected to LaunchDarkly.

If this returns false, it means that the client has not yet successfully connected to LaunchDarkly. It might still be in the process of starting up, or it might be attempting to reconnect after an unsuccessful attempt, or it might have received an unrecoverable error (such as an invalid SDK key) and given up.

is_offline() bool[source]

Returns true if the client is in offline mode.

migration_variation(key: str, context: Context, default_stage: Stage) Tuple[Stage, OpTracker][source]

This method returns the migration stage of the migration feature flag for the given evaluation context.

This method returns the default stage if there is an error or the flag does not exist. If the default stage is not a valid stage, then a default stage of ldclient.migrations.Stage.OFF will be used instead.

secure_mode_hash(context: Context) str[source]

Creates a hash string that can be used by the JavaScript SDK to identify a context.

For more information, see the documentation on Secure mode.

Parameters:

context – the evaluation context

Returns:

the hash string

track(event_name: str, context: Context, data: Any | None = None, metric_value: AnyNum | None = None)[source]

Tracks that an application-defined event occurred.

This method creates a “custom” analytics event containing the specified event name (key) and context properties. You may attach arbitrary data or a metric value to the event with the optional data and metric_value parameters.

Note that event delivery is asynchronous, so the event may not actually be sent until later; see flush().

Parameters:
  • event_name – the name of the event

  • context – the evaluation context associated with the event

  • data – optional additional data associated with the event

  • metric_value – a numeric value used by the LaunchDarkly experimentation feature in numeric custom metrics; can be omitted if this event is used by only non-numeric metrics

track_migration_op(tracker: OpTracker)[source]

Tracks the results of a migrations operation. This event includes measurements which can be used to enhance the observability of a migration within the LaunchDarkly UI.

Customers making use of the ldclient.MigrationBuilder should not need to call this method manually.

Customers not using the builder should provide this method with the tracker returned from calling migration_variation().

variation(key: str, context: Context, default: Any) Any[source]

Calculates the value of a feature flag for a given context.

Parameters:
  • key – the unique key for the feature flag

  • context – the evaluation context

  • default – the default value of the flag, to be used if the value is not available from LaunchDarkly

Returns:

the variation for the given context, or the default value if the flag cannot be evaluated

variation_detail(key: str, context: Context, default: Any) EvaluationDetail[source]

Calculates the value of a feature flag for a given context, and returns an object that describes the way the value was determined.

The reason property in the result will also be included in analytics events, if you are capturing detailed event data for this flag.

Parameters:
  • key – the unique key for the feature flag

  • context – the evaluation context

  • default – the default value of the flag, to be used if the value is not available from LaunchDarkly

Returns:

an ldclient.evaluation.EvaluationDetail object that includes the feature flag value and evaluation reason

ldclient.config module

This submodule contains the Config class for custom configuration of the SDK client.

Note that the same class can also be imported from the ldclient.client submodule.

class ldclient.config.BigSegmentsConfig(store: BigSegmentStore | None = None, context_cache_size: int = 1000, context_cache_time: float = 5, status_poll_interval: float = 5, stale_after: float = 120)[source]

Configuration options related to Big Segments.

Big Segments are a specific type of segments. For more information, read the LaunchDarkly documentation: https://docs.launchdarkly.com/home/users/big-segments

If your application uses Big Segments, you will need to create a BigSegmentsConfig that at a minimum specifies what database integration to use, and then pass the BigSegmentsConfig object as the big_segments parameter when creating a Config.

This example shows Big Segments being configured to use Redis:

from ldclient.config import Config, BigSegmentsConfig
from ldclient.integrations import Redis
store = Redis.new_big_segment_store(url='redis://localhost:6379')
config = Config(big_segments=BigSegmentsConfig(store = store))
__init__(store: BigSegmentStore | None = None, context_cache_size: int = 1000, context_cache_time: float = 5, status_poll_interval: float = 5, stale_after: float = 120)[source]
Parameters:
  • store – the implementation of ldclient.interfaces.BigSegmentStore that will be used to query the Big Segments database

  • context_cache_size – the maximum number of contexts whose Big Segment state will be cached by the SDK at any given time

  • context_cache_time – the maximum length of time (in seconds) that the Big Segment state for a context will be cached by the SDK

  • status_poll_interval – the interval (in seconds) at which the SDK will poll the Big Segment store to make sure it is available and to determine how long ago it was updated

  • stale_after – the maximum length of time between updates of the Big Segments data before the data is considered out of date

property context_cache_size: int
property context_cache_time: float
property stale_after: float
property status_poll_interval: float
property store: BigSegmentStore | None
class ldclient.config.Config(sdk_key: str, base_uri: str = 'https://app.launchdarkly.com', events_uri: str = 'https://events.launchdarkly.com', events_max_pending: int = 10000, flush_interval: float = 5, stream_uri: str = 'https://stream.launchdarkly.com', stream: bool = True, initial_reconnect_delay: float = 1, defaults: dict = {}, send_events: bool | None = None, update_processor_class: ~typing.Callable[[str, ~ldclient.config.Config, ~ldclient.interfaces.FeatureStore], ~ldclient.interfaces.UpdateProcessor] | None = None, poll_interval: float = 30, use_ldd: bool = False, feature_store: ~ldclient.interfaces.FeatureStore | None = None, feature_requester_class=None, event_processor_class: ~typing.Callable[[~ldclient.config.Config], ~ldclient.interfaces.EventProcessor] | None = None, private_attributes: ~typing.Set[str] = {}, all_attributes_private: bool = False, offline: bool = False, context_keys_capacity: int = 1000, context_keys_flush_interval: float = 300, diagnostic_opt_out: bool = False, diagnostic_recording_interval: int = 900, wrapper_name: str | None = None, wrapper_version: str | None = None, http: ~ldclient.config.HTTPConfig = <ldclient.config.HTTPConfig object>, big_segments: ~ldclient.config.BigSegmentsConfig | None = None, application: dict | None = None)[source]

Advanced configuration options for the SDK client.

To use these options, create an instance of Config and pass it to either ldclient.set_config() if you are using the singleton client, or the ldclient.client.LDClient constructor otherwise.

__init__(sdk_key: str, base_uri: str = 'https://app.launchdarkly.com', events_uri: str = 'https://events.launchdarkly.com', events_max_pending: int = 10000, flush_interval: float = 5, stream_uri: str = 'https://stream.launchdarkly.com', stream: bool = True, initial_reconnect_delay: float = 1, defaults: dict = {}, send_events: bool | None = None, update_processor_class: ~typing.Callable[[str, ~ldclient.config.Config, ~ldclient.interfaces.FeatureStore], ~ldclient.interfaces.UpdateProcessor] | None = None, poll_interval: float = 30, use_ldd: bool = False, feature_store: ~ldclient.interfaces.FeatureStore | None = None, feature_requester_class=None, event_processor_class: ~typing.Callable[[~ldclient.config.Config], ~ldclient.interfaces.EventProcessor] | None = None, private_attributes: ~typing.Set[str] = {}, all_attributes_private: bool = False, offline: bool = False, context_keys_capacity: int = 1000, context_keys_flush_interval: float = 300, diagnostic_opt_out: bool = False, diagnostic_recording_interval: int = 900, wrapper_name: str | None = None, wrapper_version: str | None = None, http: ~ldclient.config.HTTPConfig = <ldclient.config.HTTPConfig object>, big_segments: ~ldclient.config.BigSegmentsConfig | None = None, application: dict | None = None)[source]
Parameters:
  • sdk_key – The SDK key for your LaunchDarkly account. This is always required.

  • base_uri – The base URL for the LaunchDarkly server. Most users should use the default value.

  • events_uri – The URL for the LaunchDarkly events server. Most users should use the default value.

  • events_max_pending – The capacity of the events buffer. The client buffers up to this many events in memory before flushing. If the capacity is exceeded before the buffer is flushed, events will be discarded.

  • flush_interval – The number of seconds in between flushes of the events buffer. Decreasing the flush interval means that the event buffer is less likely to reach capacity.

  • stream_uri – The URL for the LaunchDarkly streaming events server. Most users should use the default value.

  • stream – Whether or not the streaming API should be used to receive flag updates. By default, it is enabled. Streaming should only be disabled on the advice of LaunchDarkly support.

  • initial_reconnect_delay – The initial reconnect delay (in seconds) for the streaming connection. The streaming service uses a backoff algorithm (with jitter) every time the connection needs to be reestablished. The delay for the first reconnection will start near this value, and then increase exponentially for any subsequent connection failures.

  • send_events – Whether or not to send events back to LaunchDarkly. This differs from offline in that it affects only the sending of client-side events, not streaming or polling for events from the server. By default, events will be sent.

  • offline – Whether the client should be initialized in offline mode. In offline mode, default values are returned for all flags and no remote network requests are made. By default, this is false.

  • poll_interval – The number of seconds between polls for flag updates if streaming is off.

  • use_ldd – Whether you are using the LaunchDarkly Relay Proxy in daemon mode. In this configuration, the client will not use a streaming connection to listen for updates, but instead will get feature state from a Redis instance. The stream and poll_interval options will be ignored if this option is set to true. By default, this is false. For more information, read the LaunchDarkly documentation: https://docs.launchdarkly.com/home/relay-proxy/using#using-daemon-mode

  • private_attributes (array) – Marks a set of attributes private. Any users sent to LaunchDarkly with this configuration active will have these attributes removed. Each item can be either the name of an attribute (“email”), or a slash-delimited path (“/address/street”) to mark a property within a JSON object value as private.

  • all_attributes_private – If true, all user attributes (other than the key) will be private, not just the attributes specified in private_attributes.

  • feature_store – A FeatureStore implementation

  • context_keys_capacity – The number of context keys that the event processor can remember at any one time, so that duplicate context details will not be sent in analytics events.

  • context_keys_flush_interval – The interval in seconds at which the event processor will reset its set of known context keys.

  • feature_requester_class – A factory for a FeatureRequester implementation taking the sdk key and config

  • event_processor_class – A factory for an EventProcessor implementation taking the config

  • update_processor_class – A factory for an UpdateProcessor implementation taking the sdk key, config, and FeatureStore implementation

  • diagnostic_opt_out – Unless this field is set to True, the client will send some diagnostics data to the LaunchDarkly servers in order to assist in the development of future SDK improvements. These diagnostics consist of an initial payload containing some details of SDK in use, the SDK’s configuration, and the platform the SDK is being run on, as well as periodic information on irregular occurrences such as dropped events.

  • diagnostic_recording_interval – The interval in seconds at which periodic diagnostic data is sent. The default is 900 seconds (every 15 minutes) and the minimum value is 60 seconds.

  • wrapper_name – For use by wrapper libraries to set an identifying name for the wrapper being used. This will be sent in HTTP headers during requests to the LaunchDarkly servers to allow recording metrics on the usage of these wrapper libraries.

  • wrapper_version – For use by wrapper libraries to report the version of the library in use. If wrapper_name is not set, this field will be ignored. Otherwise the version string will be included in the HTTP headers along with the wrapper_name during requests to the LaunchDarkly servers.

  • http – Optional properties for customizing the client’s HTTP/HTTPS behavior. See HTTPConfig.

  • application – Optional properties for setting application metadata. See application

property all_attributes_private: bool
property application: dict

An object that allows configuration of application metadata.

Application metadata may be used in LaunchDarkly analytics or other product features, but does not affect feature flag evaluations.

If you want to set non-default values for any of these fields, provide the appropriately configured dict to the {Config} object.

property base_uri: str
property big_segments: BigSegmentsConfig
property context_keys_capacity: int
property context_keys_flush_interval: float
copy_with_new_sdk_key(new_sdk_key: str) Config[source]

Returns a new Config instance that is the same as this one, except for having a different SDK key.

Parameters:

new_sdk_key – the new SDK key

property data_source_update_sink: DataSourceUpdateSink | None

Returns the component that allows a data source to push data into the SDK.

This property should only be set by the SDK. Long term access of this property is not supported; it is temporarily being exposed to maintain backwards compatibility while the SDK structure is updated.

Custom data source implementations should integrate with this sink if they want to provide support for data source status listeners.

property diagnostic_opt_out: bool
property diagnostic_recording_interval: int
property event_processor_class: Callable[[Config], EventProcessor] | None
property events_base_uri
property events_max_pending: int
property events_uri
property feature_requester_class: Callable
property feature_store: FeatureStore
property flush_interval: float
get_default(key, default)[source]
property get_latest_flags_uri
property http: HTTPConfig
property initial_reconnect_delay: float
property offline: bool
property poll_interval: float
property private_attributes: List[str]
property sdk_key: str | None
property send_events: bool
property stream: bool
property stream_base_uri
property stream_uri
property update_processor_class: Callable[[str, Config, FeatureStore], UpdateProcessor] | None
property use_ldd: bool
property wrapper_name: str | None
property wrapper_version: str | None
class ldclient.config.HTTPConfig(connect_timeout: float = 10, read_timeout: float = 15, http_proxy: str | None = None, ca_certs: str | None = None, cert_file: str | None = None, disable_ssl_verification: bool = False)[source]

Advanced HTTP configuration options for the SDK client.

This class groups together HTTP/HTTPS-related configuration properties that rarely need to be changed. If you need to set these, construct an HTTPConfig instance and pass it as the http parameter when you construct the main Config for the SDK client.

__init__(connect_timeout: float = 10, read_timeout: float = 15, http_proxy: str | None = None, ca_certs: str | None = None, cert_file: str | None = None, disable_ssl_verification: bool = False)[source]
Parameters:
  • connect_timeout – The connect timeout for network connections in seconds.

  • read_timeout – The read timeout for network connections in seconds.

  • http_proxy – Use a proxy when connecting to LaunchDarkly. This is the full URI of the proxy; for example: http://my-proxy.com:1234. Note that unlike the standard http_proxy environment variable, this is used regardless of whether the target URI is HTTP or HTTPS (the actual LaunchDarkly service uses HTTPS, but a Relay Proxy instance could use HTTP). Setting this Config parameter will override any proxy specified by an environment variable, but only for LaunchDarkly SDK connections.

  • ca_certs – If using a custom certificate authority, set this to the file path of the certificate bundle.

  • cert_file – If using a custom client certificate, set this to the file path of the certificate.

  • disable_ssl_verification – If true, completely disables SSL verification and certificate verification for secure requests. This is unsafe and should not be used in a production environment; instead, use a self-signed certificate and set ca_certs.

property ca_certs: str | None
property cert_file: str | None
property connect_timeout: float
property disable_ssl_verification: bool
property http_proxy: str | None
property read_timeout: float

ldclient.evaluation module

class ldclient.evaluation.BigSegmentsStatus[source]

Indicates that the Big Segment query involved in the flag evaluation was successful, and the segment state is considered up to date.

HEALTHY = 'HEALTHY'

Indicates that the Big Segment query involved in the flag evaluation was successful, but segment state may not be up to date.

NOT_CONFIGURED = 'NOT_CONFIGURED'

Indicates that the Big Segment query involved in the flag evaluation failed, for instance due to a database error.

STALE = 'STALE'

Indicates that Big Segments could not be queried for the flag evaluation because the SDK configuration did not include a Big Segment store.

STORE_ERROR = 'STORE_ERROR'
class ldclient.evaluation.EvaluationDetail(value: object, variation_index: int | None, reason: dict)[source]

The return type of ldclient.client.LDClient.variation_detail(), combining the result of a flag evaluation with information about how it was calculated.

__init__(value: object, variation_index: int | None, reason: dict)[source]

Constructs an instance.

is_default_value() bool[source]

Returns True if the flag evaluated to the default value rather than one of its variations.

property reason: dict

A dictionary describing the main factor that influenced the flag evaluation value. It contains the following properties:

  • kind: The general category of reason, as follows:

    • "OFF": the flag was off

    • "FALLTHROUGH": the flag was on but the user did not match any targets or rules

    • "TARGET_MATCH": the user was specifically targeted for this flag

    • "RULE_MATCH": the user matched one of the flag’s rules

    • "PREREQUISITE_FAILED": the flag was considered off because it had at least one prerequisite flag that did not return the desired variation

    • "ERROR": the flag could not be evaluated due to an unexpected error.

  • ruleIndex, ruleId: The positional index and unique identifier of the matched rule, if the kind was RULE_MATCH

  • prerequisiteKey: The flag key of the prerequisite that failed, if the kind was PREREQUISITE_FAILED

  • errorKind: further describes the nature of the error if the kind was ERROR, e.g. "FLAG_NOT_FOUND"

  • bigSegmentsStatus: describes the validity of Big Segment information, if and only if the flag evaluation required querying at least one Big Segment; otherwise it returns None. Allowable values are defined in BigSegmentsStatus. For more information, read the LaunchDarkly documentation: https://docs.launchdarkly.com/home/users/big-segments

property value: object

The result of the flag evaluation. This will be either one of the flag’s variations or the default value that was passed to the ldclient.client.LDClient.variation_detail() method.

property variation_index: int | None

The index of the returned value within the flag’s list of variations, e.g. 0 for the first variation – or None if the default value was returned.

class ldclient.evaluation.FeatureFlagsState(valid: bool)[source]

A snapshot of the state of all feature flags with regard to a specific user, generated by calling the ldclient.client.LDClient.all_flags_state() method. Serializing this object to JSON, using the to_json_dict() method or jsonpickle, will produce the appropriate data structure for bootstrapping the LaunchDarkly JavaScript client. See the JavaScript SDK Reference Guide on Bootstrapping.

__init__(valid: bool)[source]
add_flag(flag_state, with_reasons, details_only_if_tracked)[source]
get_flag_reason(key: str) dict | None[source]

Returns the evaluation reason for an individual feature flag at the time the state was recorded.

Parameters:

key – the feature flag key

Returns:

a dictionary describing the reason; None if reasons were not recorded, or if there was no such flag

get_flag_value(key: str) object[source]

Returns the value of an individual feature flag at the time the state was recorded.

Parameters:

key – the feature flag key

Returns:

the flag’s value; None if the flag returned the default value, or if there was no such flag

to_json_dict() dict[source]

Returns a dictionary suitable for passing as JSON, in the format used by the LaunchDarkly JavaScript SDK. Use this method if you are passing data to the front end in order to “bootstrap” the JavaScript client.

to_json_string() str[source]

Same as to_json_dict, but serializes the JSON structure into a string.

to_values_map() dict[source]

Returns a dictionary of flag keys to flag values. If the flag would have evaluated to the default value, its value will be None.

Do not use this method if you are passing data to the front end to “bootstrap” the JavaScript client. Instead, use to_json_dict().

property valid: bool

True if this object contains a valid snapshot of feature flag state, or False if the state could not be computed (for instance, because the client was offline or there was no user).

ldclient.migrations module

class ldclient.migrations.ExecutionOrder(value)[source]

Depending on the migration stage, reads may operate against both old and new origins. In this situation, the execution order can be defined to specify how these individual reads are coordinated.

PARALLEL = 'parallel'

PARALLEL executes both reads in separate threads. This helps reduce total run time at the cost of the thread overhead.

RANDOM = 'random'

Like SERIAL, RANDOM ensures that one read is completed before the subsequent read is executed. However, the order in which they are executed is randomly decided.

SERIAL = 'serial'

SERIAL execution order ensures that the authoritative read completes before the non-authoritative read is executed.

static from_str(order: str) ExecutionOrder | None[source]

This method will create a Stage enum corresponding to the given string. If the string doesn’t map to a stage, None will returned.

class ldclient.migrations.MigrationConfig(old: Callable[[Any | None], Result], new: Callable[[Any | None], Result], comparison: Callable[[Any, Any], bool] | None = None)[source]

A migration config stores references to callable methods which execute customer defined read or write operations on old or new origins of information. For read operations, an optional comparison function also be defined.

__init__(old: Callable[[Any | None], Result], new: Callable[[Any | None], Result], comparison: Callable[[Any, Any], bool] | None = None)[source]
property comparison: Callable[[Any, Any], bool] | None

Optional callable which receives two objects of any kind and returns a boolean representing equality.

The result of this comparison can be sent upstream to LaunchDarkly to enhance migration observability.

property new: Callable[[Any | None], Result]

# Callable which receives a nullable payload parameter and returns an # ldclient.Result. # # This function call should affect the new migration origin when # called.

property old: Callable[[Any | None], Result]

Callable which receives a nullable payload parameter and returns an ldclient.Result.

This function call should affect the old migration origin when called.

@return [#call]

class ldclient.migrations.Migrator[source]

A migrator is the interface through which migration support is executed. A migrator is configured through the MigratorBuilder.

abstract read(key: str, context: Context, default_stage: Stage, payload: Any | None = None) OperationResult[source]

Uses the provided flag key and context to execute a migration-backed read operation.

Parameters:
  • key – The migration flag key to use when determining the current stage

  • context – The context to use when evaluating the flag

  • default_stage – A default stage to fallback to if one cannot be determined

  • payload – An optional payload to be passed through to the appropriate read method

abstract write(key: str, context: Context, default_stage: Stage, payload: Any | None = None) WriteResult[source]

Uses the provided flag key and context to execute a migration-backed write operation.

Parameters:
  • key – The migration flag key to use when determining the current stage

  • context – The context to use when evaluating the flag

  • default_stage – A default stage to fallback to if one cannot be determined

  • payload – An optional payload to be passed through to the appropriate write method

class ldclient.migrations.MigratorBuilder(client: LDClient)[source]

The migration builder is used to configure and construct an instance of a Migrator. This migrator can be used to perform LaunchDarkly assisted technology migrations through the use of migration-based feature flags.

__init__(client: LDClient)[source]
build() Migrator | str[source]

Build constructs a Migrator instance to support migration-based reads and writes. A string describing any failure conditions will be returned if the build fails.

read(old: Callable[[Any | None], Result], new: Callable[[Any | None], Result], comparison: Callable[[Any, Any], bool] | None = None) MigratorBuilder[source]

Read can be used to configure the migration-read behavior of the resulting Migrator instance.

Users are required to provide two different read methods – one to read from the old migration origin, and one to read from the new origin. Additionally, customers can opt-in to consistency tracking by providing a comparison function.

Depending on the migration stage, one or both of these read methods may be called.

The read methods should accept a single nullable parameter. This parameter is a payload passed through the Migrator.read() method. This method should return a ldclient.Result instance.

The consistency method should accept 2 parameters of any type. These parameters are the results of executing the read operation against the old and new origins. If both operations were successful, the consistency method will be invoked. This method should return true if the two parameters are equal, or false otherwise.

Parameters:
  • old – The function to execute when reading from the old origin

  • new – The function to execute when reading from the new origin

  • comparison – An optional function to use for comparing the results from two origins

read_execution_order(order: ExecutionOrder) MigratorBuilder[source]

The read execution order influences the parallelism and execution order for read operations involving multiple origins.

track_errors(enabled: bool) MigratorBuilder[source]

Enable or disable error tracking for migration operations. This error information can be sent upstream to LaunchDarkly to enhance migration visibility.

track_latency(enabled: bool) MigratorBuilder[source]

Enable or disable latency tracking for migration operations. This latency information can be sent upstream to LaunchDarkly to enhance migration visibility.

write(old: Callable[[Any | None], Result], new: Callable[[Any | None], Result]) MigratorBuilder[source]

Write can be used to configure the migration-write behavior of the resulting Migrator instance.

Users are required to provide two different write methods – one to write to the old migration origin, and one to write to the new origin.

Depending on the migration stage, one or both of these write methods may be called.

The write methods should accept a single nullable parameter. This parameter is a payload passed through the Migrator.write() method. This method should return a ldclient.Result instance.

Parameters:
  • old – The function to execute when writing to the old origin

  • new – The function to execute when writing to the new origin

class ldclient.migrations.OpTracker(key: str, flag: FeatureFlag | None, context: Context, detail: EvaluationDetail, default_stage: Stage)[source]

An OpTracker is responsible for managing the collection of measurements that which a user might wish to record throughout a migration-assisted operation.

Example measurements include latency, errors, and consistency.

The OpTracker is not expected to be instantiated directly. Consumers should instead call ldclient.client.LDClient.migration_variation() and use the returned tracker instance.

__init__(key: str, flag: FeatureFlag | None, context: Context, detail: EvaluationDetail, default_stage: Stage)[source]
build() MigrationOpEvent | str[source]

Creates an instance of MigrationOpEvent(). This event data can be provided to ldclient.client.LDClient.track_migration_op() to relay this metric information upstream to LaunchDarkly services.

Returns:

A MigrationOpEvent() or a string describing the type of failure.

consistent(is_consistent: Callable[[], bool]) OpTracker[source]

Allows recording the results of a consistency check.

This method accepts a callable which should take no parameters and return a single boolean to represent the consistency check results for a read operation.

A callable is provided in case sampling rules do not require consistency checking to run. In this case, we can avoid the overhead of a function by not using the callable.

Parameters:

is_consistent – closure to return result of comparison check

error(origin: Origin) OpTracker[source]

Allows recording whether an error occurred during the operation.

Parameters:

origin – Designation for the old or new origin.

invoked(origin: Origin) OpTracker[source]

Allows recording which origins were called during a migration.

Parameters:

origin – Designation for the old or new origin.

latency(origin: Origin, duration: timedelta) OpTracker[source]

Allows tracking the recorded latency for an individual operation.

Parameters:
  • origin – Designation for the old or new origin.

  • duration – Duration measurement.

operation(op: Operation) OpTracker[source]

Sets the migration related operation associated with these tracking measurements.

Parameters:

op – The read or write operation symbol.

class ldclient.migrations.Operation(value)[source]

The operation enum is used to record the type of migration operation that occurred.

READ = 'read'

READ represents a read-only operation on an origin of data.

A read operation carries the implication that it can be executed in parallel against multiple origins.

WRITE = 'write'

WRITE represents a write operation on an origin of data.

A write operation implies that execution cannot be done in parallel against multiple origins.

class ldclient.migrations.OperationResult(origin: Origin, result: Result)[source]

The OperationResult wraps a ldclient.Result pair an origin with a result.

__init__(origin: Origin, result: Result)[source]

This constructor should be considered private. Consumers of this class should use one of the two factory methods provided. Direct instantiation should follow the below expectations:

  • Successful operations have contain a value, but MUST NOT contain an error or an exception value.

  • Failed operations MUST contain an error string, and may optionally include an exception.

Parameters:
  • value – A result value when the operation was a success

  • error – An error describing the cause of the failure

  • exception – An optional exception if the failure resulted from an exception being raised

property origin: Origin
class ldclient.migrations.Origin(value)[source]

The origin enum is used to denote which source of data should be affected by a particular operation.

NEW = 'new'

The NEW origin is the source of data we are migrating to. When the migration is complete, this source of data will be the source of truth.

OLD = 'old'

The OLD origin is the source of data we are migrating from. When the migration is complete, this source of data will be unused.

class ldclient.migrations.Stage(value)[source]

Stage denotes one of six possible stages a technology migration could be a part of, progressing through the following order.

Stage.OFF -> Stage.DUALWRITE -> Stage.SHADOW -> Stage.LIVE -> Stage.RAMPDOWN -> Stage.COMPLETE

COMPLETE = 'complete'

The migration is finished. Origin.NEW is authoritative for reads and writes

DUALWRITE = 'dualwrite'

Write to both Origin.OLD and Origin.NEW, Origin.OLD is authoritative for reads

LIVE = 'live'

Both Origin.NEW and Origin.OLD versions run with a preference for Origin.NEW

OFF = 'off'

The migration hasn’t started. Origin.OLD is authoritative for reads and writes

RAMPDOWN = 'rampdown'

Only read from Origin.NEW, write to Origin.OLD and Origin.NEW

SHADOW = 'shadow'

Both Origin.NEW and Origin.OLD versions run with a preference for Origin.OLD

static from_str(stage: str) Stage | None[source]

This method will create a Stage enum corresponding to the given string. If the string doesn’t map to a stage, OFF will be used.