Core API¶
ldclient module¶
The ldclient module contains the most common top-level entry points for the SDK.
-
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. Thenget()
will return the same sharedldclient.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.
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 toldclient.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()
andldclient.get()
. However, you may also call the constructor directly if you need to maintain multiple instances.Client instances are thread-safe.
-
alias
(current_user, previous_user)[source]¶ Associates two users for analytics purposes.
This can be helpful in the situation where a person is represented by multiple LaunchDarkly users. This may happen, for example, when a person initially logs into an application, the person might be represented by an anonymous user prior to logging in and a different user after logging in, as denoted by a different user key.
- Parameters
current_user (
dict
) – The new version of a user.previous_user (
dict
) – The old version of a user.
-
all_flags_state
(user, **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 (
dict
) – the end user requesting the feature flagskwargs – 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
- 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
¶ 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.- Return type
-
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 ofldclient.config.Config
. Callingflush()
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.
-
identify
(user)[source]¶ Registers the user.
This simply creates an analytics event that will transmit the given user properties to LaunchDarkly, so that the user will be visible on your dashboard even if you have not evaluated any flags for that user. It has no other effect.
- Parameters
user (
dict
) – attributes of the user 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
-
secure_mode_hash
(user)[source]¶ Computes an HMAC signature of a user signed with the client’s SDK key, for use with the JavaScript SDK.
For more information, see the JavaScript SDK Reference Guide on Secure mode.
- Parameters
user (
dict
) – the attributes of the user- Return type
str
- Returns
a hash string that can be passed to the front end
-
track
(event_name, user, data=None, metric_value=None)[source]¶ Tracks that a user performed an event.
LaunchDarkly automatically tracks pageviews and clicks that are specified in the Goals section of the dashboard. This can be used to track custom goals or other events that do not currently have goals.
- Parameters
event_name (
str
) – the name of the event, which may correspond to a goal in A/B testsuser (
dict
) – the attributes of the userdata (
Optional
[Any
]) – optional additional data associated with the eventmetric_value (
Optional
[~AnyNum]) – 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. This field will also be returned as part of the custom event for Data Export.
-
variation
(key, user, default)[source]¶ Determines the variation of a feature flag for a user.
- Parameters
key (
str
) – the unique key for the feature flaguser (
dict
) – a dictionary containing parameters for the end user requesting the flagdefault (
Any
) – the default value of the flag, to be used if the value is not available from LaunchDarkly
- Return type
Any
- Returns
one of the flag’s variation values, or the default value
-
variation_detail
(key, user, default)[source]¶ Determines the variation of a feature flag for a user, like
variation()
, but also provides additional information about how this value was calculated, in the form of anldclient.flag.EvaluationDetail
object.Calling this method also causes the “reason” data to be included in analytics events, if you are capturing detailed event data for this flag.
- Parameters
key (
str
) – the unique key for the feature flaguser (
dict
) – a dictionary containing parameters for the end user requesting the flagdefault (
Any
) – the default value of the flag, to be used if the value is not available from LaunchDarkly
- Return type
- Returns
an object describing the result
-
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, user_cache_size=1000, user_cache_time=5, status_poll_interval=5, stale_after=120)[source]¶ Configuration options related to Big Segments.
Big Segments are a specific type of user 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))
-
property
stale_after
¶ - Return type
float
-
property
status_poll_interval
¶ - Return type
float
-
property
store
¶ - Return type
Optional
[BigSegmentStore
]
-
property
user_cache_size
¶ - Return type
int
-
property
user_cache_time
¶ - Return type
float
-
property
-
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, events_enabled=True, update_processor_class=None, poll_interval=30, use_ldd=False, feature_store=None, feature_requester_class=None, event_processor_class=None, private_attribute_names={}, all_attributes_private=False, offline=False, user_keys_capacity=1000, user_keys_flush_interval=300, inline_users_in_events=False, 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 eitherldclient.set_config()
if you are using the singleton client, or theldclient.client.LDClient
constructor otherwise.-
property
all_attributes_private
¶ - Return type
bool
-
property
application
¶ 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.
- Return type
dict
-
property
base_uri
¶ - Return type
str
-
property
big_segments
¶ - Return type
-
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
-
property
diagnostic_opt_out
¶ - Return type
bool
-
property
diagnostic_recording_interval
¶ - Return type
int
-
property
event_processor_class
¶ - Return type
Optional
[Callable
[[Config
],EventProcessor
]]
-
property
events_base_uri
¶
-
property
events_enabled
¶ - Return type
bool
-
property
events_max_pending
¶ - Return type
int
-
property
events_uri
¶
-
property
feature_requester_class
¶ - Return type
Callable
-
property
feature_store
¶ - Return type
-
property
flush_interval
¶ - Return type
float
-
property
get_latest_flags_uri
¶
-
property
http
¶ - Return type
-
property
initial_reconnect_delay
¶ - Return type
float
-
property
inline_users_in_events
¶ - Return type
bool
-
property
offline
¶ - Return type
bool
-
property
poll_interval
¶ - Return type
float
-
property
private_attribute_names
¶ - Return type
list
-
property
sdk_key
¶ - Return type
Optional
[str
]
-
property
send_events
¶ - Return type
bool
-
property
stream
¶ - Return type
bool
-
property
stream_base_uri
¶
-
property
stream_uri
¶
-
property
update_processor_class
¶ - Return type
Optional
[Callable
[[str
,Config
,FeatureStore
],UpdateProcessor
]]
-
property
use_ldd
¶ - Return type
bool
-
property
user_keys_capacity
¶ - Return type
int
-
property
user_keys_flush_interval
¶ - Return type
float
-
property
wrapper_name
¶ - Return type
Optional
[str
]
-
property
wrapper_version
¶ - Return type
Optional
[str
]
-
property
-
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.-
property
ca_certs
¶ - Return type
Optional
[str
]
-
property
cert_file
¶ - Return type
Optional
[str
]
-
property
connect_timeout
¶ - Return type
float
-
property
disable_ssl_verification
¶ - Return type
bool
-
property
http_proxy
¶ - Return type
Optional
[str
]
-
property
read_timeout
¶ - Return type
float
-
property
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.-
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
¶ 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 wasRULE_MATCH
prerequisiteKey
: The flag key of the prerequisite that failed, if the kind wasPREREQUISITE_FAILED
errorKind
: further describes the nature of the error if the kind wasERROR
, 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 inBigSegmentsStatus
. For more information, read the LaunchDarkly documentation: https://docs.launchdarkly.com/home/users/big-segments
- Return type
dict
-
property
value
¶ 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.- Return type
object
-
property
variation_index
¶ 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.
- Return type
Optional
[int
]
-
-
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 theto_json_dict()
method orjsonpickle
, will produce the appropriate data structure for bootstrapping the LaunchDarkly JavaScript client. See the JavaScript SDK Reference Guide on Bootstrapping.-
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
¶ 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).
- Return type
bool
-