Skip to content

Add types to code snippets for hooks #13437

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/platforms/python/configuration/filtering/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Suppose that you wish prevent all errors of type `ZeroDivisionError` from being
import sentry_sdk
from sentry_sdk.types import Event, Hint

def my_before_send(event: Event, hint: Hint) -> Event | None:
def before_send(event: Event, hint: Hint) -> Event | None:
# Filter out all ZeroDivisionError events.
# Note that the exception type is available in the hint,
# but we should handle the case where the exception info
Expand All @@ -48,7 +48,7 @@ def my_before_send(event: Event, hint: Hint) -> Event | None:
sentry_sdk.init(
# ...

before_send=my_before_send,
before_send=before_send,
)
```

Expand Down
3 changes: 2 additions & 1 deletion docs/platforms/python/profiling/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,9 @@ Transaction-based profiling only runs in tandem with performance transactions th

```python
import sentry_sdk
from sentry_sdk.types import SamplingContext

def profiles_sampler(sampling_context):
def profiles_sampler(sampling_context: SamplingContext) -> float:
# ...
# return a number between 0 and 1 or a boolean

Expand Down
25 changes: 20 additions & 5 deletions docs/platforms/python/tracing/configure-sampling/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ In distributed systems, implementing inheritance logic when trace information is
1. Prioritizing Critical User Flows

```python
def traces_sampler(sampling_context):
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
# Use the parent sampling decision if we have an incoming trace.
# Note: we strongly recommend respecting the parent sampling decision,
# as this ensures your traces will be complete!
Expand Down Expand Up @@ -79,7 +82,10 @@ sentry_sdk.init(
2. Handling Different Environments and Error Rates

```python
def traces_sampler(sampling_context):
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
# Use the parent sampling decision if we have an incoming trace.
# Note: we strongly recommend respecting the parent sampling decision,
# as this ensures your traces will be complete!
Expand Down Expand Up @@ -130,7 +136,10 @@ with sentry_sdk.start_transaction(name="GET /api/users", op="http.request") as t
3. Controlling Sampling Based on User and Transaction Properties

```python
def traces_sampler(sampling_context):
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
# Use the parent sampling decision if we have an incoming trace.
# Note: we strongly recommend respecting the parent sampling decision,
# as this ensures your traces will be complete!
Expand Down Expand Up @@ -183,7 +192,10 @@ with sentry_sdk.start_transaction(name="GET /api/users", op="http.request") as t
4. Complex Business Logic Sampling

```python
def traces_sampler(sampling_context):
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
# Use the parent sampling decision if we have an incoming trace.
# Note: we strongly recommend respecting the parent sampling decision,
# as this ensures your traces will be complete!
Expand Down Expand Up @@ -241,7 +253,10 @@ with sentry_sdk.start_transaction(name="Process Payment", op="payment.process")
5. Performance-Based Sampling

```python
def traces_sampler(sampling_context):
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
# Use the parent sampling decision if we have an incoming trace.
# Note: we strongly recommend respecting the parent sampling decision,
# as this ensures your traces will be complete!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,10 @@ with sentry_sdk.start_span(name="my-span") as span:
To attach data attributes to the transaction and all its spans, you can use <PlatformLink to="/configuration/filtering/#using-before-send-transaction">`before_send_transaction`</PlatformLink>:

```python
def my_before_send_transaction(event, hint):
import sentry_sdk
from sentry_sdk.types import Event, Hint

def before_send_transaction(event: Event, hint: Hint) -> Event | None:
# Set the data attribute "foo" to "bar" on every span belonging to this
# transaction event
for span in event["spans"]:
Expand All @@ -284,9 +287,8 @@ def my_before_send_transaction(event, hint):

return event


sentry_sdk.init(
traces_sample_rate=1.0,
before_send_transaction=my_before_send_transaction,
before_send_transaction=before_send_transaction,
)
```
26 changes: 13 additions & 13 deletions docs/platforms/python/tracing/span-lifecycle/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ import sentry_sdk

with sentry_sdk.start_span(op="process", name="Process Data"):
# This code is tracked in the "Process Data" span

with sentry_sdk.start_span(op="task", name="Validate Input"):
# This is now a child span of "Process Data"
validate_data()

with sentry_sdk.start_span(op="task", name="Transform Data"):
# Another child span
transform_data()
Expand All @@ -71,7 +71,7 @@ import sentry_sdk
with sentry_sdk.start_span(op="db", name="Query Users") as span:
# Perform a database query
users = db.query("SELECT * FROM users")

# You can set data on the span
span.set_data("user_count", len(users))
```
Expand Down Expand Up @@ -113,7 +113,7 @@ import sentry_sdk

with sentry_sdk.start_transaction(name="Background Task", op="task") as transaction:
# Your code here

# You can add child spans to the transaction
with sentry_sdk.start_span(op="subtask", name="Data Processing"):
# Process data
Expand All @@ -132,7 +132,7 @@ import sentry_sdk
with sentry_sdk.start_span(op="db", name="Query Users") as span:
# Execute the query
users = db.query("SELECT * FROM users WHERE active = true")

# You can add more data during execution
span.set_data("result_count", len(users))
```
Expand All @@ -156,32 +156,33 @@ To add attributes to all spans, use the `before_send_transaction` callback:

```python
import sentry_sdk
from sentry_sdk.types import Event, Hint

def before_send_transaction(event):
def before_send_transaction(event: Event, hint: Hint) -> Event | None:
# Add attributes to the root span (transaction)
if "trace" in event.get("contexts", {}):
if "data" not in event["contexts"]["trace"]:
event["contexts"]["trace"]["data"] = {}

event["contexts"]["trace"]["data"].update({
"app_version": "1.2.3",
"environment_region": "us-west-2"
})

# Add attributes to all child spans
for span in event.get("spans", []):
if "data" not in span:
span["data"] = {}

span["data"].update({
"component_version": "2.0.0",
"deployment_stage": "production"
})

return event

sentry_sdk.init(
# Your other Sentry configuration options here
# ...
before_send_transaction=before_send_transaction
)
```
Expand All @@ -202,7 +203,7 @@ with sentry_sdk.start_span(op="http.client", name="Fetch User Data"):
# Database operation
with sentry_sdk.start_span(op="db", name="Save User"):
db.execute(
"INSERT INTO users (name, email) VALUES (%s, %s)",
"INSERT INTO users (name, email) VALUES (%s, %s)",
(user.name, user.email),
)

Expand Down Expand Up @@ -233,4 +234,3 @@ with sentry_sdk.start_span(op="task", name="Process Payment") as span:
# Span will automatically be marked as failed when an exception occurs
raise
```

13 changes: 8 additions & 5 deletions docs/platforms/python/tracing/span-metrics/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ if span:
# Add individual metrics
span.set_data("database.rows_affected", 42)
span.set_data("cache.hit_rate", 0.85)

# Add multiple metrics at once
span.set_data({
"memory.heap_used": 1024000,
Expand Down Expand Up @@ -70,12 +70,15 @@ For detailed examples of how to implement span metrics in common scenarios, see
To consistently add metrics across all spans in your application, you can use the `before_send_transaction` callback:

```python
def before_send_transaction(event):
import sentry_sdk
from sentry_sdk.types import Event, Hint

def before_send_transaction(event: Event, hint: Hint) -> Event | None:
# Add metrics to the root span
if "trace" in event.get("contexts", {}):
if "data" not in event["contexts"]["trace"]:
event["contexts"]["trace"]["data"] = {}

event["contexts"]["trace"]["data"].update({
"app.version": "1.2.3",
"environment.region": "us-west-2"
Expand All @@ -85,7 +88,7 @@ def before_send_transaction(event):
for span in event.get("spans", []):
if "data" not in span:
span["data"] = {}

span["data"].update({
"app.component_version": "2.0.0",
"app.deployment_stage": "production"
Expand All @@ -94,7 +97,7 @@ def before_send_transaction(event):
return event

sentry_sdk.init(
# Your other Sentry configuration options here
# ...
before_send_transaction=before_send_transaction
)
```
Expand Down
7 changes: 4 additions & 3 deletions docs/platforms/python/tracing/troubleshooting/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,19 @@ You can define a custom `before_send_transaction` callback to modify transaction
```python
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.types import Event, Hint

def transaction_processor(event, hint):
def transaction_processor(event: Event, hint: Hint) -> Event | None:
if event.get("type") == "transaction":
# Extract path from transaction name
transaction_name = event.get("transaction", "")

# Remove variable IDs from URLs to reduce cardinality
if "/user/" in transaction_name:
# Convert /user/123/ to /user/:id/
import re
event["transaction"] = re.sub(r'/user/\d+/', '/user/:id/', transaction_name)

return event

sentry_sdk.init(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
```python
import sentry_sdk
from sentry_sdk.types import Breadcrumb, BreadcrumbHint

def before_breadcrumb(crumb, hint):
def before_breadcrumb(crumb: Breadcrumb, hint: BreadcrumbHint) -> Breadcrumb | None:
if 'log_record' in hint:
crumb['data']['thread'] = hint['log_record'].threadName

return crumb

sentry_sdk.init(
Expand Down
15 changes: 10 additions & 5 deletions platform-includes/configuration/before-send-fingerprint/python.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
```python
import sentry_sdk
from sentry_sdk.types import Event, Hint

def before_send(event: Event, hint: Hint) -> Event | None:
if 'exc_info' not in hint:
return event

exception = hint['exc_info'][1]

if isinstance(exception, DatabaseUnavailable):
event['fingerprint'] = ['database-unavailable']

def before_send(event, hint):
if 'exc_info' in hint:
exc_type, exc_value, tb = hint['exc_info']
if isinstance(exc_value, DatabaseUnavailable):
event['fingerprint'] = ['database-unavailable']
return event

sentry_sdk.init(
Expand Down
15 changes: 10 additions & 5 deletions platform-includes/configuration/before-send-hint/python.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
```python
import sentry_sdk
from sentry_sdk.types import Event, Hint

def before_send(event: Event, hint: Hint) -> Event | None:
if 'exc_info' not in hint:
return event

exception = hint['exc_info'][1]

if isinstance(exception, DatabaseUnavailable):
event['fingerprint'] = ['database-unavailable']

def before_send(event, hint):
if 'exc_info' in hint:
exc_type, exc_value, tb = hint['exc_info']
if isinstance(exc_value, DatabaseUnavailable):
event['fingerprint'] = ['database-unavailable']
return event

sentry_sdk.init(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ In Python, a function can be used to modify the transaction event or return a ne

```python
import sentry_sdk
from sentry_sdk.types import Event, Hint

def strip_sensitive_data(event, hint):
def strip_sensitive_data(event: Event, hint: Hint) -> Event | None:
# modify event here
return event

Expand All @@ -16,9 +17,11 @@ sentry_sdk.init(
Addtionally, you may filter out transaction events based on the request URL, like `/healthcheck`.

```python
import sentry_sdk
from sentry_sdk.types import Event, Hint
from urllib.parse import urlparse

def filter_transactions(event, hint):
def filter_transactions(event: Event, hint: Hint) -> Event | None:
url_string = event["request"]["url"]
parsed_url = urlparse(url_string)

Expand Down
4 changes: 2 additions & 2 deletions platform-includes/configuration/error-sampler/python.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import sentry_sdk
from sentry_sdk.types import Event, Hint


def my_error_sampler(event: Event, hint: Hint) -> float:
def error_sampler(event: Event, hint: Hint) -> float:
error_class = hint["exc_info"][0]

if error_class == MyException:
Expand All @@ -17,6 +17,6 @@ def my_error_sampler(event: Event, hint: Hint) -> float:

sentry_sdk.init(
# ...
error_sampler=my_error_sampler,
error_sampler=error_sampler,
)
```
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
```python
import sentry_sdk
from sentry_sdk.types import Breadcrumb, BreadcrumbHint

def before_breadcrumb(crumb, hint):
def before_breadcrumb(crumb: Breadcrumb, hint: BreadcrumbHint) -> Breadcrumb | None:
if crumb['category'] == 'a.spammy.Logger':
return None

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
```python
def traces_sampler(sampling_context):
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
if "...":
# Drop this transaction, by setting its sample rate to 0%
return 0
Expand Down
Loading
Loading