AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

feature-flags-python

PostHog feature flags for Python applications

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--feature-flags-python at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 4

references/adding-feature-flag-code.md · 48000

re the feature_flag_request_timeout_seconds parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds.

Ruby

PostHog AI

posthog = PostHog::Client.new({
   # rest of your configuration...
   feature_flag_request_timeout_seconds: 3 # Time in seconds. Default is 3.
})

Error handling

When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:

Ruby

PostHog AI

def handle_feature_flag(client, flag_key, distinct_id)
    begin
        is_enabled = client.is_feature_enabled(flag_key, distinct_id)
        puts "Feature flag '#{flag_key}' for user '#{distinct_id}' is #{is_enabled ? 'enabled' : 'disabled'}"
        return is_enabled
    rescue => e
        puts "Error fetching feature flag '#{flag_key}': #{e.message}"
        # Optionally, you can return a default value or throw the error
        # return false # Default to disabled
        raise e
    end
end
# Usage example
try
    flag_enabled = handle_feature_flag(client, 'new-feature', 'user-123')
    if flag_enabled
        # Implement new feature logic
    else
        # Implement old feature logic
    end
rescue => e
    # Handle the error at a higher level
    puts 'Feature flag check failed, using default behavior'
    # Implement fallback logic
end

Go

There are 2 steps to implement feature flags in Go:

Step 1: Evaluate the feature flag value

Boolean feature flags

Go

PostHog AI

isMyFlagEnabled, err := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
    Key:        "flag-key",
    DistinctId: "distinct_id_of_your_user",
})
if err != nil {
    // Handle error (e.g. capture error and fallback to default behavior)
}
if isMyFlagEnabled == true {
    // Do something differently for this user
}

Multivariate feature flags

Go

PostHog AI

enabledVariant, err := client.GetFeatureFlag(posthog.FeatureFlagPayload{
    Key:        "flag-key",
    DistinctId: "distinct_id_of_your_user",
})
if err != nil {
    // Handle error (e.g. capture error and fallback to default behavior)
}
if enabledVariant == "variant-key" { // replace 'variant-key' with the key of your variant
    // Do something differently for this user
}

Step 2: Include feature flag information when capturing events

If you want use your feature flag to breakdown or filter events in your insights, you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event.

Note: This step is only required for events captured using our server-side SDKs or API.

There are two methods you can use to include feature flag information in your events:

Method 1: Include the $feature/feature_flag_name property

In the event properties, include $feature/feature_flag_name: variant_key:

Go

PostHog AI

client.Enqueue(posthog.Capture{
  DistinctId: "distinct_id_of_your_user",
  Event:      "event_name",
  Properties: posthog.NewProperties().
    Set("$feature/feature-flag-key", "variant-key"), // replace feature-flag-key with your flag key. Replace 'variant-key' with the key of your variant
})

Method 2: Set SendFeatureFlags to true

The Capture struct has an optional field SendFeatureFlags, which is set to false by default. This parameter controls whether feature flag information is sent with the event.

Basic usage

Setting SendFeatureFlags to true will include feature flag information with the event:

Go

PostHog AI

client.Enqueue(posthog.Capture{
  DistinctId: "distinct_id_of_your_user",
  Event:      "event_name",
  SendFeatureFlags: true,
})

Advanced usage (v1.6.1+)

As of version 1.6.1, SendFeatureFlags can also accept a SendFeatureFlagsOptions struct for more granular control:

Go

PostHog AI

client.Enqueue(posthog.Capture{
  DistinctId: "distinct_id_of_your_user",
  Event:      "event_name",
  SendFeatureFlags: posthog.SendFeatureFlagsOptions{
    OnlyEvaluateLocally: true,
    PersonProperties: map[string]interface{}{
      "plan": "premium",
    },
    GroupProperties: map[string]map[string]interface{}{
      "org": {
        "tier": "enterprise",
      },
    },
  },
})

Performance considerations

  • With local evaluation: When local evaluation is configured, setting SendFeatureFlags: true will not make additional server requests. Instead, it uses the locally cached feature flags, and it provides an interface for including person and/or group properties needed to evaluate the flags in the context of the event, if required.

  • Without local evaluation: PostHog will make an additional request to fetch feature flag information before capturing the event, which adds delay.

Breaking change in v1.6.1

Prior to version 1.6.1, feature flags were automatically sent with events when using local evaluation, even when SendFeatureFlags was not explicitly set. This behavior has been removed in v1.6.1 to be more predictable and explicit.

If you were relying on this automatic behavior, you must now explicitly set SendFeatureFlags: true to continue sending feature flags with your events.

Fetching all flags for a user

You can fetch all flag values for a single user by calling GetAllFlags().

This is useful when you need to fetch multiple flag values and don't want to make multiple requests.

Go

PostHog AI

featureVariants, err := client.GetAllFlags(posthog.FeatureFlagPayloadNoKey{
        DistinctId: "distinct_id_of_your_user",
})

Sending $feature_flag_called events

Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:

  1. You call GetFeatureFlag() or IsFeatureEnabled(), AND
  2. It's a new user, or the value of the flag has changed.

Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing $feature_flag_called events to be sent again when calling GetFeatureFlag or IsFeatureEnabled. PostHog is built to handle this, and so duplicate $feature_flag_called events won't affect your analytics.

You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.

To disable it (pre v1.6.1), set the SendFeatureFlagEvents argument in your function call, like so:

Go

PostHog AI

sendFeatureFlags := false
isMyFlagEnabled, err := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
    Key:                    "flag-key",
    DistinctId:             "distinct_id_of_your_user",
    SendFeatureFlagEvents:  &sendFeatureFlags,
})

Versions after v1.6.1 have this feature disabled by default.

Advanced: Overriding server properties

Sometimes, you may want to evaluate feature flags using person properties, groups, or group properties that haven't been ingested yet, or were set incorrectly earlier.

You can provide properties to evaluate the flag with by using the person properties, groups, and group properties arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server.

For example:

Go

PostHog AI

enabledVariant, err := client.GetFeatureFlag(
    FeatureFlagPayload{
        Key:        "flag-key",
        DistinctId: "distinct_id_of_the_user",
        Groups: posthog.NewGroups().
            Set("your_group_type", "your_group_id").
            Set("another_group_type", "your_group_id"),
        PersonProperties: posthog.NewProperties().
            Set("property_name", "value"),
        GroupProperties: map[string]map[string]interface{}{
            "your_group_type": {
                "group_property_name": "value",
            },
            "another_group_type": {
                "group_property_name": "value",
            },
        },
    },
)

Overriding GeoIP properties

By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties.

You can override GeoIP properties by including them in the person_properties parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location.

The following GeoIP properties can be overridden:

  • $geoip_country_code
  • $geoip_country_name
  • $geoip_city_name
  • $geoip_city_confidence
  • $geoip_continent_code
  • $geoip_continent_name
  • $geoip_latitude
  • $geoip_longitude
  • $geoip_postal_code
  • $geoip_subdivision_1_code
  • $geoip_subdivision_1_name
  • $geoip_subdivision_2_code
  • $geoip_subdivision_2_name
  • $geoip_subdivision_3_code
  • $geoip_subdivision_3_name
  • $geoip_time_zone

Simply include any of these properties in the person_properties parameter alongside your other person properties when calling feature flags.

Request timeout

You can configure the FeatureFlagRequestTimeout parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds.

Go

PostHog AI

client, _ := posthog.NewWithConfig(
   os.Getenv("<ph_project_token>"),
   posthog.Config{
      PersonalApiKey:            "your personal API key", // Optional, but much more performant.  If this token is not supplied, then fetching feature flag values will be slower.
      Endpoint:                  "https://us.i.posthog.com",
      FeatureFlagRequestTimeout: 3 // Time in seconds. Default is 3.
   },
)

Error handling

When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:

Go

PostHog AI

func handleFeatureFlag(client *posthog.Client, flagKey string, distinctId string) {
    flag, err := client.GetFeatureFlag(posthog.FeatureFlagPayload{
        Key:        flagKey,
        DistinctId: distinctId,
    })
    if err != nil {
        // Handle the error appropriately
        log.Printf("Error fetching feature flag: %v", err)
        return
    }
    // Use the flag value as needed
    fmt.Printf("Feature flag '%s' for user '%s': %s\n", flagKey, distinctId, flag)
}

React Native

There are two ways to implement feature flags in React Native:

  1. Using hooks.
  2. Loading the flag directly.

Method 1: Using hooks

Example 1: Boolean feature flags

React Native

PostHog AI

import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
    const booleanFlag = useFeatureFlag('key-for-your-boolean-flag')
    if (booleanFlag === undefined) {
        // the response is undefined if the flags are being loaded
        return null
    }
    // Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload
    return booleanFlag ? <Text>Testing feature 😄</Text> : <Text>Not Testing feature 😢</Text>
}

Example 2: Multivariate feature flags

React Native

PostHog AI

import { useFeatureFlag } from 'posthog-react-native'
const MyComponent = () => {
    const multiVariantFeature = useFeatureFlag('key-for-your-multivariate-flag')
    if (multiVariantFeature === undefined) {
        // the response is undefined if the flags are being loaded
        return null
    } else if (multiVariantFeature === 'variant-name') { // replace 'variant-name' with the name of your variant
      // Do something
    }
    // Optional use the 'useFeatureFlagWithPayload' hook for fetching the feature flag payload
    return <div/>
}

Method 2: Loading the flag directly

React Native

PostHog AI

// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.isFeatureEnabled('key-for-your-boolean-flag')
// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.getFeatureFlag('key-for-your-boolean-flag')
// Multivariant feature flags are returned as a string
posthog.getFeatureFlag('key-for-your-multivariate-flag')
// Optional fetch the payload returns 'JsonType' or undefined if not loaded yet or if there was a problem loading
posthog.getFeatureFlagPayload('key-for-your-multivariate-flag')

Ensuring flags are loaded before usage

Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.

This means that for most screens, the feature flags are available immediately — except for the first time a user visits.

To handle this, you can use the onFeatureFlags callback to wait for the feature flag request to finish:

React Native

PostHog AI

posthog.onFeatureFlags((flags) => {
  // feature flags are guaranteed to be available at this point
  if (posthog.isFeatureEnabled('flag-key')) {
    // do something
  }
})

Reloading flags

PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.

If want to manually trigger a refresh, you can call reloadFeatureFlagsAsync():

React Native

PostHog AI

posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))

Or when you want to trigger the reload, but don't care about the result:

React Native

PostHog AI

posthog.reloadFeatureFlags()

Feature flag caching

The React Native SDK caches feature flag values in AsyncStorage. Cached values persist indefinitely with no TTL until updated by a successful API call. This enables offline support and reduces latency, but means inactive users may see stale flag values from their last session.

For example, if a user last opened your app when a flag was false, that value remains cached even after you roll it out to 100%. When they reopen the app, the SDK returns the cached false first, then fetches the fresh true value from the API.

To ensure fresh flag values:

React Native

PostHog AI

// Force refresh on app start
await posthog.reloadFeatureFlagsAsync()

Or clear cached values for inactive users:

React Native

PostHog AI

if (lastActiveDate < migrationDate) {
  posthog.reset() // Clears all cached data
}

Request timeout

You can configure the featureFlagsRequestTimeoutMs parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 10 seconds.

React Native

PostHog AI

export const posthog = new PostHog('<ph_project_token>', {
  // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
  host: 'https://us.i.posthog.com',
  featureFlagsRequestTimeoutMs: 10000 // Time in milliseconds. Default is 10000 (10 seconds).
})

Error handling

When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:

React Native

PostHog AI

function handleFeatureFlag(client, flagKey, distinctId) {
    try {
        const isEnabled = client.isFeatureEnabled(flagKey, distinctId);
        console.log(`Feature flag '${flagKey}' for user '${distinctId}' is ${isEnabled ? 'enabled' : 'disabled'}`);
        return isEnabled;
    } catch (error) {
        console.error(`Error fetching feature flag '${flagKey}': ${error.message}`);
        // Optionally, you can return a default value or throw the error
        // return false; // Default to disabled
        throw error;
    }
}
// Usage example
try {
    const flagEnabled = handleFeatureFlag(client, 'new-feature', 'user-123');
    if (flagEnabled) {
        // Implement new feature logic
    } else {
        // Implement old feature logic
    }
} catch (error) {
    // Handle the error at a higher level
    console.error('Feature flag check failed, using default behavior');
    // Implement fallback logic
}

Overriding server properties

Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:

React Native

PostHog AI

posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})

Note that these are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation.

Whenever you set these properties, we also trigger a reload of feature flags to ensure we have the latest values. You can disable this by passing in the optional parameter for reloading:

React Native

PostHog AI

posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)

At any point, you can reset these properties by calling resetPersonPropertiesForFlags:

React Native

PostHog AI

posthog.resetPersonPropertiesForFlags()

The same holds for group properties:

React Native

PostHog AI

// set properties for a group
posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})
// reset properties for all groups:
posthog.resetGroupPropertiesForFlags()

Note: You don't need to add the group names here, since these properties are automatically attached to the current group (set via posthog.group()). When you change the group, these properties are reset.

Automatic overrides

Whenever you call posthog.identify with person properties, we automatically add these properties to flag evaluation calls to help determine the correct flag values. The same is true for when you call posthog.group().

Default overridden properties

By default, we always override some properties based on the user IP address.

The list of properties that this overrides:

  1. $geoip_city_name
  2. $geoip_country_name
  3. $geoip_country_code
  4. $geoip_continent_name
  5. $geoip_continent_code
  6. $geoip_postal_code
  7. $geoip_time_zone

This enables any geolocation-based flags to work without manually setting these properties.

Android

Boolean feature flags

Kotlin

PostHog AI

import com.posthog.PostHog
if (PostHog.isFeatureEnabled("flag-key")) {
    // Do something differently for this user
    // Optional: fetch the payload
    val matchedFlagPayload = PostHog.getFeatureFlagPayload("flag-key")
}

Multivariate feature flags

Kotlin

PostHog AI

import com.posthog.PostHog
if (PostHog.getFeatureFlag("flag-key") == "variant-key") { // replace 'variant-key' with the key of your variant
    // Do something differently for this user
    // Optional: fetch the payload
    val matchedFlagPayload = PostHog.getFeatureFlagPayload("flag-key")
}

Ensuring flags are loaded before usage

Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.

This means that for most screens, the feature flags are available immediately – except for the first time a user visits.

To handle this, you can use the onFeatureFlags callback to wait for the feature flag request to finish:

Kotlin

PostHog AI

import com.posthog.PostHog
import com.posthog.android.PostHogAndroidConfig
import com.posthog.PostHogOnFeatureFlags
// During SDK initialization
val config = PostHogAndroidConfig(apiKey = "<ph_project_token>").apply {
    onFeatureFlags = PostHogOnFeatureFlags {
        if (PostHog.isFeatureEnabled("flag-key")) {
            // do something
        }
    }
}
// And/Or manually the SDK is initialized
PostHog.reloadFeatureFlags {
    if (PostHog.isFeatureEnabled("flag-key")) {
        // do something
    }
}

Reloading feature flags

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:

Kotlin

PostHog AI

import com.posthog.PostHog
PostHog.reloadFeatureFlags()

iOS

Boolean feature flags

Swift

PostHog AI

if (PostHogSDK.shared.isFeatureEnabled("flag-key")) {
    // Do something differently for this user
    // Optional: fetch the payload
    let matchedFlagPayload = PostHogSDK.shared.getFeatureFlagPayload("flag-key")
}

Multivariate feature flags

Swift

PostHog AI

if (PostHogSDK.shared.getFeatureFlag("flag-key") as? String == "variant-key") { // replace "variant-key" with the key of your variant
    // Do something differently for this user
    // Optional: fetch the payload
    let matchedFlagPayload = PostHogSDK.shared.getFeatureFlagPayload("flag-key")
}

Reloading feature flags

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:

Swift

PostHog AI

PostHogSDK.shared.reloadFeatureFlags()

Ensuring flags are loaded before usage

Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.

This means that for most screens, the feature flags are available immediately – except for the first time a user visits.

To handle this, you can use the didReceiveFeatureFlags notification to wait for the feature flag request to finish:

Swift

PostHog AI

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // register for `didReceiveFeatureFlags` notification before SDK initialization
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(receiveFeatureFlags),
            name: PostHogSDK.didReceiveFeatureFlags,
            object: nil
        )
        let POSTHOG_API_KEY = "<ph_project_token>"
        // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
        let POSTHOG_HOST = "https://us.i.posthog.com"
        let config = PostHogConfig(apiKey: POSTHOG_API_KEY, host: POSTHOG_HOST)
        PostHogSDK.shared.setup(config)
        return true
    }
    // The "receiveFeatureFlags" method will be called when the SDK receives the feature flags from the server.
    @objc func receiveFeatureFlags() {
        print("receiveFeatureFlags called")
    }
}

Alternatively, you can use the completion block of the reloadFeatureFlags(_:) method. This allows you to execute logic immediately after the flags are reloaded:

Swift

PostHog AI

// Reload feature flags and check if a specific feature is enabled
PostHogSDK.shared.reloadFeatureFlags {
    if PostHogSDK.shared.isFeatureEnabled("flag-key") {
        // do something
    }
}

Flutter

Boolean feature flags

Dart

PostHog AI

if (await Posthog().isFeatureEnabled('