Core API

ldclient module

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

class ldclient.Context(kind, key, name=None, anonymous=False, attributes=None, private_attributes=None, multi_contexts=None, allow_empty_key=False, error=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)[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 (str) – the context key

Return type

ContextBuilder

Returns

a new builder

See

create()

See

create_multi()

classmethod builder_from_context(context)[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 (Context) – the context to copy from

Return type

ContextBuilder

Returns

a new builder

classmethod create(key, kind=None)[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 (str) – the context key

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

Return type

Context

Returns

a context

See

builder()

See

create_multi()

classmethod create_multi(*contexts)[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 (Context) – the individual contexts

Return type

Context

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: Optional[str]

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)[source]

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

If the dictionary has a “kind” property, then it is interpreted as a context using the LaunchDarkly JSON schema for contexts. If it does not have a “kind” property, it is interpreted as a context with “user” kind using the somewhat different LaunchDarkly JSON schema for users in older LaunchDarkly SDKs.

Parameters

props (dict) – the context/user properties

Return type

Context

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)[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 (str) – the desired attribute name

Return type

Any

Returns

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

See

ldclient.ContextBuilder.set()

get_individual_context(kind)[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 (Union[int, str]) – the index or string value of a context kind

Return type

Optional[Context]

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()[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.

Return type

ContextMultiBuilder

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: Optional[str]

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()[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()[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().

Return type

str

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, copy_from=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 (str) – the context key

anonymous(anonymous)[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 (bool) – true if the context should be excluded from the LaunchDarkly database

Return type

ContextBuilder

Returns

the builder

See

ldclient.Context.anonymous

build()[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.

Return type

Context

Returns

a new ldclient.Context

key(key)[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 (str) – the context key

Return type

ContextBuilder

Returns

the builder

kind(kind)[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 (str) – the context kind

Return type

ContextBuilder

Returns

the builder

name(name)[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 (Optional[str]) – the context name (None to unset the attribute)

Return type

ContextBuilder

Returns

the builder

private(*attributes)[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 (str) – attribute names or references to mark as private

Return type

ContextBuilder

Returns

the builder

set(attribute, value)[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 (str) – the attribute name to set

  • value (Any) – the value to set

Return type

ContextBuilder

Returns

the builder

try_set(attribute, value)[source]

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

Parameters
  • attribute (str) – the attribute name to set

  • value (Any) – the value to set

Return type

bool

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)[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 (Context) – the context to add

Return type

ContextMultiBuilder

Returns

the builder

build()[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.

Return type

Context

Returns

a new Context

ldclient.get()[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.

Return type

LDClient

ldclient.set_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 (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, start_wait=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, **kwargs)[source]

Returns an object that encapsulates the state of all feature flags for a given user, 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
  • user – the end user 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

Return type

FeatureFlagsState

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 user is None or has no key)

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.

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()[source]

Returns the configured SDK key.

Return type

Optional[str]

identify(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.

If you pass a dictionary of user attributes instead of a ldclient.Context, the SDK will convert the user to a Context. There is some overhead to this conversion, so it is more efficient to pass a Context.

Parameters

context (Union[Context, dict]) – the context to register

is_initialized()[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.

Return type

bool

is_offline()[source]

Returns true if the client is in offline mode.

Return type

bool

secure_mode_hash(context)[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 (Union[Context, dict]) – the evaluation context or user

Return type

str

Returns

the hash string

track(event_name, context, data=None, metric_value=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().

If you pass a dictionary of user attributes instead of a ldclient.Context, the SDK will convert the user to a Context. There is some overhead to this conversion, so it is more efficient to pass a Context.

Parameters
  • event_name (str) – the name of the event

  • context (Union[dict, Context]) – the evaluation context or user associated with the event

  • data (Optional[Any]) – optional additional data associated with the event

  • metric_value (Optional[TypeVar(AnyNum, int, float, complex)]) – 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

variation(key, context, default)[source]

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

If you pass a dictionary of user attributes instead of a ldclient.Context, the SDK will convert the user to a Context. There is some overhead to this conversion, so it is more efficient to pass a Context.

Parameters
  • key (str) – the unique key for the feature flag

  • context (Union[Context, dict]) – the evaluation context or user

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

Return type

Any

Returns

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

variation_detail(key, context, default)[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.

If you pass a dictionary of user attributes instead of a ldclient.Context, the SDK will convert the user to a Context. There is some overhead to this conversion, so it is more efficient to pass a Context.

Parameters
  • key (str) – the unique key for the feature flag

  • context (Union[Context, dict]) – the evaluation context or user

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

Return type

EvaluationDetail

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=None, context_cache_size=1000, context_cache_time=5, user_cache_size=None, user_cache_time=None, status_poll_interval=5, stale_after=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=None, context_cache_size=1000, context_cache_time=5, user_cache_size=None, user_cache_time=None, status_poll_interval=5, stale_after=120)[source]
Parameters
  • store (Optional[BigSegmentStore]) – the implementation of ldclient.interfaces.BigSegmentStore that will be used to query the Big Segments database

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

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

  • user_cache_size (Optional[int]) – deprecated alias for context_cache_size

  • user_cache_time (Optional[float]) – deprecated alias for context_cache_time

  • status_poll_interval (float) – 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 (float) – 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: Optional[BigSegmentStore]
property user_cache_size: int

Deprecated alias for context_cache_size.

property user_cache_time: float

Deprecated alias for context_cache_time.

class ldclient.config.Config(sdk_key, base_uri='https://app.launchdarkly.com', events_uri='https://events.launchdarkly.com', events_max_pending=10000, flush_interval=5, stream_uri='https://stream.launchdarkly.com', stream=True, initial_reconnect_delay=1, defaults={}, send_events=None, update_processor_class=None, poll_interval=30, use_ldd=False, feature_store=None, feature_requester_class=None, event_processor_class=None, private_attributes={}, private_attribute_names={}, all_attributes_private=False, offline=False, context_keys_capacity=1000, context_keys_flush_interval=300, user_keys_capacity=None, user_keys_flush_interval=None, diagnostic_opt_out=False, diagnostic_recording_interval=900, wrapper_name=None, wrapper_version=None, http=<ldclient.config.HTTPConfig object>, big_segments=None, application=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, base_uri='https://app.launchdarkly.com', events_uri='https://events.launchdarkly.com', events_max_pending=10000, flush_interval=5, stream_uri='https://stream.launchdarkly.com', stream=True, initial_reconnect_delay=1, defaults={}, send_events=None, update_processor_class=None, poll_interval=30, use_ldd=False, feature_store=None, feature_requester_class=None, event_processor_class=None, private_attributes={}, private_attribute_names={}, all_attributes_private=False, offline=False, context_keys_capacity=1000, context_keys_flush_interval=300, user_keys_capacity=None, user_keys_flush_interval=None, diagnostic_opt_out=False, diagnostic_recording_interval=900, wrapper_name=None, wrapper_version=None, http=<ldclient.config.HTTPConfig object>, big_segments=None, application=None)[source]
Parameters
  • sdk_key (str) – The SDK key for your LaunchDarkly account. This is always required.

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

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

  • events_max_pending (int) – 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 (float) – 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 (str) – The URL for the LaunchDarkly streaming events server. Most users should use the default value.

  • stream (bool) – 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 (float) – 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 (Optional[bool]) – 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 (bool) – 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 (float) – The number of seconds between polls for flag updates if streaming is off.

  • use_ldd (bool) – 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_attribute (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.

  • private_attribute_names (array) – Deprecated alias for private_attributes (“names” is no longer strictly accurate because these could also be attribute reference paths).

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

  • feature_store (Optional[FeatureStore]) – A FeatureStore implementation

  • context_keys_capacity (int) – 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 (float) – The interval in seconds at which the event processor will reset its set of known context keys.

  • user_keys_capacity (Optional[int]) – Deprecated alias for context_keys_capacity.

  • user_keys_flush_interval (Optional[float]) – Deprecated alias for context_keys_flush_interval.

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

  • event_processor_class (Optional[Callable[[Config], EventProcessor]]) – A factory for an EventProcessor implementation taking the config

  • update_processor_class (Optional[Callable[[str, Config, FeatureStore], UpdateProcessor]]) – A factory for an UpdateProcessor implementation taking the sdk key, config, and FeatureStore implementation

  • diagnostic_opt_out (bool) – 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 (int) – 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 (Optional[str]) – 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 (Optional[str]) – 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 (HTTPConfig) – Optional properties for customizing the client’s HTTP/HTTPS behavior. See HTTPConfig.

  • application (Optional[dict]) – 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)[source]

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

Parameters

new_sdk_key (str) – the new SDK key

Return type

Config

property diagnostic_opt_out: bool
property diagnostic_recording_interval: int
property event_processor_class: Optional[Callable[[Config], EventProcessor]]
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_attribute_names: List[str]
property private_attributes: List[str]
property sdk_key: Optional[str]
property send_events: bool
property stream: bool
property stream_base_uri
property stream_uri
property update_processor_class: Optional[Callable[[str, Config, FeatureStore], UpdateProcessor]]
property use_ldd: bool
property user_keys_capacity: int

Deprecated name for context_keys_capacity.

property user_keys_flush_interval: float

Deprecated name for context_keys_flush_interval.

property wrapper_name: Optional[str]
property wrapper_version: Optional[str]
class ldclient.config.HTTPConfig(connect_timeout=10, read_timeout=15, http_proxy=None, ca_certs=None, cert_file=None, disable_ssl_verification=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=10, read_timeout=15, http_proxy=None, ca_certs=None, cert_file=None, disable_ssl_verification=False)[source]
Parameters
  • connect_timeout (float) – The connect timeout for network connections in seconds.

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

  • http_proxy (Optional[str]) – 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 (Optional[str]) – If using a custom certificate authority, set this to the file path of the certificate bundle.

  • cert_file (Optional[str]) – If using a custom client certificate, set this to the file path of the certificate.

  • disable_ssl_verification (bool) – 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: Optional[str]
property cert_file: Optional[str]
property connect_timeout: float
property disable_ssl_verification: bool
property http_proxy: Optional[str]
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, variation_index, reason)[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, variation_index, reason)[source]

Constructs an instance.

is_default_value()[source]

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

Return type

bool

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: Optional[int]

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)[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)[source]
add_flag(flag_state, with_reasons, details_only_if_tracked)[source]
get_flag_reason(key)[source]

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

Parameters

key (str) – the feature flag key

Return type

Optional[dict]

Returns

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

get_flag_value(key)[source]

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

Parameters

key (str) – the feature flag key

Return type

object

Returns

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

to_json_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.

Return type

dict

to_json_string()[source]

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

Return type

str

to_values_map()[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().

Return type

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).