Skip to content

feat: Add context helpers to Client#681

Merged
marandaneto merged 5 commits into
mainfrom
fix/client-context-methods-289
Jun 19, 2026
Merged

feat: Add context helpers to Client#681
marandaneto merged 5 commits into
mainfrom
fix/client-context-methods-289

Conversation

@marandaneto

@marandaneto marandaneto commented Jun 19, 2026

Copy link
Copy Markdown
Member

💡 Motivation and Context

Closes #289.

Custom Client instances already had new_context(), but context helpers such as tagging, context identity, session IDs, device IDs, and scoped decorators were only available through module-level helpers. This made custom-client usage less ergonomic and inconsistent with the module-level API.

This PR adds thin Client wrappers for the existing context helpers without changing the contextvars storage model.

💚 How did you test it?

  • uvx ruff format posthog/client.py posthog/test/test_client.py
  • uv run --extra dev python .github/scripts/check_public_api.py --write
  • uv run --extra dev python .github/scripts/check_public_api.py
  • uv run --extra test pytest -q posthog/test/test_contexts.py posthog/test/test_client.py
  • git diff --check

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

A Pi worker agent implemented the user-directed fix for issue #289. The change intentionally keeps context storage unchanged and exposes only thin custom-client wrappers around the existing context helper APIs; Client.scoped() uses Client.new_context() so exception capture remains bound to the custom client.

@marandaneto marandaneto self-assigned this Jun 19, 2026
@greptile-apps

greptile-apps Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
posthog/client.py:488-523
**`Client.scoped()` duplicates `contexts.scoped()`**

`Client.scoped()` is a near-verbatim copy of `contexts.scoped()` — the only difference is `self.new_context()` instead of `new_context()`, which threads `client=self` through to `new_context()`. Adding a `client` parameter to `contexts.scoped()` would let `Client.scoped()` become a one-liner delegate (`return _context_scoped(fresh=fresh, capture_exceptions=capture_exceptions, client=self)`) and remove the ~18 lines of duplicated async/sync branching, in line with the OnceAndOnlyOnce simplicity rule.

### Issue 2 of 3
posthog/test/test_client.py:2530-2553
**No async path tested for `Client.scoped()`**

`Client.scoped()` branches on `inspect.iscoroutinefunction` and generates a distinct `async_wrapper`, but only the synchronous path is exercised here. A test decorating an `async def` function and running it with `asyncio.run()` (mirroring the approach in `test_contexts.py`) would cover the async branch.

### Issue 3 of 3
posthog/test/test_client.py:2496-2553
**Two structurally identical tests could be parameterised**

`test_client_context_helpers_apply_to_capture` and `test_client_scoped_context_helpers_apply_to_capture` assert the same properties on the captured event — they differ only in how the context is entered (`with client.new_context(fresh=True)` vs `@client.scoped(fresh=True)`). Per the project's test style, parameterising over the context-creation mechanism would express both cases without repeating the assertion block.

Reviews (1): Last reviewed commit: "fix: Add context helpers to Client" | Re-trigger Greptile

Comment thread posthog/client.py Outdated
Comment thread posthog/test/test_client.py
Comment thread posthog/test/test_client.py
@github-actions

github-actions Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-06-19 14:58:07 UTC
Duration: 540130ms

✅ All Tests Passed!

45/45 tests passed


Capture Tests

29/29 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields 519ms
Format Validation.Event Has Uuid 10007ms
Format Validation.Event Has Lib Properties 10007ms
Format Validation.Distinct Id Is String 10006ms
Format Validation.Token Is Present 10007ms
Format Validation.Custom Properties Preserved 10007ms
Format Validation.Event Has Timestamp 10007ms
Retry Behavior.Retries On 503 18020ms
Retry Behavior.Does Not Retry On 400 12004ms
Retry Behavior.Does Not Retry On 401 10005ms
Retry Behavior.Respects Retry After Header 16014ms
Retry Behavior.Implements Backoff 32028ms
Retry Behavior.Retries On 500 16000ms
Retry Behavior.Retries On 502 16012ms
Retry Behavior.Retries On 504 16010ms
Retry Behavior.Max Retries Respected 32016ms
Deduplication.Generates Unique Uuids 10003ms
Deduplication.Preserves Uuid On Retry 16016ms
Deduplication.Preserves Uuid And Timestamp On Retry 23019ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 16006ms
Deduplication.No Duplicate Events In Batch 10004ms
Deduplication.Different Events Have Different Uuids 10007ms
Compression.Sends Gzip When Enabled 10009ms
Batch Format.Uses Proper Batch Structure 10007ms
Batch Format.Flush With No Events Sends Nothing 5010ms
Batch Format.Multiple Events Batched Together 10006ms
Error Handling.Does Not Retry On 403 12008ms
Error Handling.Does Not Retry On 413 10008ms
Error Handling.Retries On 408 14013ms

Feature_Flags Tests

16/16 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 9502ms
Request Payload.Flags Request Uses V2 Query Param 10006ms
Request Payload.Flags Request Hits Flags Path Not Decide 10007ms
Request Payload.Flags Request Omits Authorization Header 10007ms
Request Payload.Token In Flags Body Matches Init 10007ms
Request Payload.Groups Round Trip 10007ms
Request Payload.Groups Default To Empty Object 10006ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It 10007ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 10007ms
Request Payload.Disable Geoip Omitted Defaults To False 10007ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 10006ms
Request Lifecycle.No Flags Request On Init Alone 5003ms
Request Lifecycle.No Flags Request On Normal Capture 10507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 9512ms
Request Lifecycle.Mock Response Value Is Returned To Caller 10002ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 10509ms

@marandaneto marandaneto changed the title fix: Add context helpers to Client feat: Add context helpers to Client Jun 19, 2026
@marandaneto marandaneto marked this pull request as ready for review June 19, 2026 13:09
@marandaneto marandaneto requested a review from a team as a code owner June 19, 2026 13:09
@greptile-apps

greptile-apps Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
posthog/client.py:503-514
**`name` vs `key` parameter name inconsistency**

The module-level `tag(key, value)` in `contexts.py` documents its first argument as `key`, but `Client.tag` names it `name`. Positional callers are unaffected, but anyone who switches between the module-level and client APIs and tries to call `client.tag(key="foo", value="bar")` will get a `TypeError`. Aligning the parameter name to `key` would keep the two APIs consistent.

### Issue 2 of 2
posthog/client.py:516-562
**Setters added, getter counterparts omitted**

The PR exposes `set_context_session`, `set_context_device_id`, and `identify_context` on `Client`, but not their read-back counterparts `get_context_session_id`, `get_context_distinct_id`, and `get_context_device_id`. `get_tags` was included, so the setter/getter pairing is asymmetric. Custom-client users who need to read the current session or device ID back are forced to reach for the module-level functions, which is exactly the ergonomic gap this PR aims to close.

Reviews (2): Last reviewed commit: "mark client context helpers as minor" | Re-trigger Greptile

@ioannisj ioannisj left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LG

…thods-289

# Conflicts:
#	posthog/contexts.py
#	references/public_api_snapshot.txt
@marandaneto marandaneto enabled auto-merge (squash) June 19, 2026 14:49
@marandaneto marandaneto merged commit bfafeba into main Jun 19, 2026
30 checks passed
@marandaneto marandaneto deleted the fix/client-context-methods-289 branch June 19, 2026 14:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Availability of module-level functions on Client

2 participants