Advanced: Custom Cohort Handlers
Sometimes, the events you want to analyze are not simple, single events but rather a combination of several events. For example, you might want to define a cohort of "highly engaged users" as users who are active AND have used either the web OR iOS client.
Instead of performing these complex bitwise operations every time you query, you can define a custom handler. This allows you to assign a simple name (e.g., 'active_web_ios') to a complex query and use that name directly in the cohort analysis form and functions.
set_custom_handler()
The set_custom_handler function registers a callback that defines how to construct a complex event.
from bitmapist import cohort, DayEvents, WeekEvents, MonthEvents, YearEvents
# Define the callback function
def active_web_ios_handler(key, cls, cls_args):
"""
This handler returns users who were 'active'
AND used either the 'web' OR 'ios' client.
"""
active_users = cls("active", *cls_args)
web_users = cls("web", *cls_args)
ios_users = cls("ios", *cls_args)
# The | and & operators perform bitwise OR and AND
return active_users & (web_users | ios_users)
# Register the handler with a unique name
cohort.set_custom_handler("active_web_ios", active_web_ios_handler)
The callback receives three arguments:
key: The string name of the handler (e.g.,'active_web_ios').cls: The time-based event class being used for the query (DayEvents,WeekEvents, etc.).cls_args: A tuple of arguments to pass to theclsconstructor (e.g.,(2023, 1, 1, 'default')).
Your handler function should return a bitmapist event object (which can be a combination of other objects via bitwise operations).
Using a Custom Handler
Once registered, you can use the handler's name just like any other event name in the cohort module.
# In the form generation
selections = [
('Active on Web or iOS', 'active_web_ios'),
('Regular Active', 'active')
]
html_form = cohort.render_html_form(
action_url='/cohort',
selections1=selections,
selections2=selections
)
# When fetching data, the cohort module will automatically
# call your handler when it encounters the 'active_web_ios' key.
data = cohort.get_dates_data(
select1='active_web_ios',
select2='task:completed',
time_group='weeks'
)
This powerful feature allows you to encapsulate complex business logic and present it as a simple, selectable option in your analytics tools.