Skip to content

Commit 09c3d4a

Browse files
committed
Fix up type annotation
1 parent 0c4746f commit 09c3d4a

File tree

8 files changed

+65
-123
lines changed

8 files changed

+65
-123
lines changed

posthog/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
from posthog.client import Client
66
from posthog.exception_capture import Integrations # noqa: F401
7+
from posthog.types import FeatureFlag, FlagsAndPayloads
78
from posthog.version import VERSION
8-
from posthog.types import FlagsAndPayloads
99

1010
__version__ = VERSION
1111

@@ -404,7 +404,7 @@ def get_feature_flag(
404404
only_evaluate_locally=False, # type: bool
405405
send_feature_flag_events=True, # type: bool
406406
disable_geoip=None, # type: Optional[bool]
407-
) -> str | bool | None:
407+
) -> Optional[FeatureFlag]:
408408
"""
409409
Get feature flag variant for users. Used with experiments.
410410
Example:
@@ -447,7 +447,7 @@ def get_all_flags(
447447
group_properties={}, # type: dict
448448
only_evaluate_locally=False, # type: bool
449449
disable_geoip=None, # type: Optional[bool]
450-
) -> dict[str, str | bool] | None:
450+
) -> Optional[dict[str, FeatureFlag]]:
451451
"""
452452
Get all flags for a given user.
453453
Example:
@@ -478,7 +478,7 @@ def get_feature_flag_payload(
478478
only_evaluate_locally=False,
479479
send_feature_flag_events=True,
480480
disable_geoip=None, # type: Optional[bool]
481-
) -> str:
481+
) -> Optional[str]:
482482
return _proxy(
483483
"get_feature_flag_payload",
484484
key=key,

posthog/client.py

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import sys
77
import warnings
88
from datetime import datetime, timedelta
9-
from typing import Any
9+
from typing import Any, Optional, Union
1010
from uuid import UUID, uuid4
1111

1212
import distro # For Linux OS detection
@@ -18,28 +18,20 @@
1818
from posthog.exception_utils import exc_info_from_error, exceptions_from_error_tuple, handle_in_app
1919
from posthog.feature_flags import InconclusiveMatchError, match_feature_flag_properties
2020
from posthog.poller import Poller
21-
from posthog.request import (
22-
DEFAULT_HOST,
23-
APIError,
24-
batch_post,
25-
decide,
26-
determine_server_host,
27-
get,
28-
remote_config,
29-
DecideResponse,
30-
)
31-
from posthog.utils import SizeLimitedDict, clean, guess_timezone, remove_trailing_slash
32-
from posthog.version import VERSION
21+
from posthog.request import DEFAULT_HOST, APIError, batch_post, decide, determine_server_host, get, remote_config
3322
from posthog.types import (
34-
FlagsAndPayloads,
23+
DecideResponse,
3524
FeatureFlag,
36-
FlagValue,
3725
FlagMetadata,
38-
to_values,
39-
to_payloads,
40-
to_flags_and_payloads,
26+
FlagsAndPayloads,
27+
FlagValue,
4128
normalize_decide_response,
29+
to_flags_and_payloads,
30+
to_payloads,
31+
to_values,
4232
)
33+
from posthog.utils import SizeLimitedDict, clean, guess_timezone, remove_trailing_slash
34+
from posthog.version import VERSION
4335

4436
try:
4537
import queue
@@ -265,7 +257,7 @@ def identify(self, distinct_id=None, properties=None, context=None, timestamp=No
265257

266258
def get_feature_variants(
267259
self, distinct_id, groups=None, person_properties=None, group_properties=None, disable_geoip=None
268-
) -> dict[str, str | bool]:
260+
) -> dict[str, Union[bool, str]]:
269261
"""
270262
Get feature flag variants for a distinct_id by calling decide.
271263
"""
@@ -352,7 +344,7 @@ def capture(
352344
msg["properties"]["$groups"] = groups
353345

354346
extra_properties: dict[str, Any] = {}
355-
feature_variants: dict[str, bool | str] | None = {}
347+
feature_variants: Optional[dict[str, Union[bool, str]]] = {}
356348
if send_feature_flags:
357349
try:
358350
feature_variants = self.get_feature_variants(distinct_id, groups, disable_geoip=disable_geoip)
@@ -820,7 +812,7 @@ def get_feature_flag(
820812
only_evaluate_locally=False,
821813
send_feature_flag_events=True,
822814
disable_geoip=None,
823-
) -> FlagValue | None:
815+
) -> Optional[FlagValue]:
824816
"""
825817
Get a feature flag value for a key by evaluating locally or remotely
826818
depending on whether local evaluation is enabled and the flag can be
@@ -859,7 +851,7 @@ def get_feature_flag(
859851
self._capture_feature_flag_called(
860852
distinct_id,
861853
key,
862-
response,
854+
response or False,
863855
None,
864856
flag_was_locally_evaluated,
865857
groups,
@@ -877,7 +869,7 @@ def _locally_evaluate_flag(
877869
groups: dict[str, str],
878870
person_properties: dict[str, str],
879871
group_properties: dict[str, str],
880-
) -> FlagValue | None:
872+
) -> Optional[FlagValue]:
881873
if self.feature_flags is None and self.personal_api_key:
882874
self.load_feature_flags()
883875
response = None
@@ -949,7 +941,7 @@ def get_feature_flag_payload(
949941
self._capture_feature_flag_called(
950942
distinct_id,
951943
key,
952-
response,
944+
response or False,
953945
payload,
954946
flag_was_locally_evaluated,
955947
groups,
@@ -967,33 +959,33 @@ def _get_feature_flag_details_from_decide(
967959
groups: dict[str, str],
968960
person_properties: dict[str, str],
969961
group_properties: dict[str, str],
970-
disable_geoip: bool | None,
971-
) -> tuple[FeatureFlag | None, str]:
962+
disable_geoip: Optional[bool],
963+
) -> tuple[Optional[FeatureFlag], Optional[str]]:
972964
"""
973965
Calls /decide and returns the flag details and request id
974966
"""
975967
resp_data = self.get_decide(distinct_id, groups, person_properties, group_properties, disable_geoip)
976968
request_id = resp_data.get("requestId")
977969
flags = resp_data.get("flags")
978-
flag_details = flags.get(key)
970+
flag_details = flags.get(key) if flags else None
979971
return flag_details, request_id
980972

981973
def _capture_feature_flag_called(
982974
self,
983975
distinct_id: str,
984976
key: str,
985977
response: FlagValue,
986-
payload: str | None,
978+
payload: Optional[str],
987979
flag_was_locally_evaluated: bool,
988980
groups: dict[str, str],
989-
disable_geoip: bool | None,
990-
request_id: str | None,
991-
flag_details: FeatureFlag | None,
981+
disable_geoip: Optional[bool],
982+
request_id: Optional[str],
983+
flag_details: Optional[FeatureFlag],
992984
):
993985
feature_flag_reported_key = f"{key}_{str(response)}"
994986

995987
if feature_flag_reported_key not in self.distinct_ids_feature_flags_reported[distinct_id]:
996-
properties = {
988+
properties: dict[str, Any] = {
997989
"$feature_flag": key,
998990
"$feature_flag_response": response,
999991
"locally_evaluated": flag_was_locally_evaluated,
@@ -1043,7 +1035,7 @@ def get_remote_config_payload(self, key: str):
10431035
except Exception as e:
10441036
self.log.exception(f"[FEATURE FLAGS] Unable to get decrypted feature flag payload: {e}")
10451037

1046-
def _compute_payload_locally(self, key: str, match_value: FlagValue) -> str | None:
1038+
def _compute_payload_locally(self, key: str, match_value: FlagValue) -> Optional[str]:
10471039
payload = None
10481040

10491041
if self.feature_flags_by_key is None:
@@ -1068,7 +1060,7 @@ def get_all_flags(
10681060
group_properties={},
10691061
only_evaluate_locally=False,
10701062
disable_geoip=None,
1071-
) -> dict[str, bool | str] | None:
1063+
) -> Optional[dict[str, Union[bool, str]]]:
10721064
response = self.get_all_flags_and_payloads(
10731065
distinct_id,
10741066
groups=groups,

posthog/request.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@
33
from datetime import date, datetime
44
from gzip import GzipFile
55
from io import BytesIO
6-
from typing import Any, Optional, Union, cast
6+
from typing import Any, Optional, Union
77

88
import requests
99
from dateutil.tz import tzutc
1010

11-
from posthog.types import DecideResponse, FeatureFlag, FlagValue
1211
from posthog.utils import remove_trailing_slash
1312
from posthog.version import VERSION
1413

posthog/test/test_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
from posthog.client import Client
1111
from posthog.request import APIError
1212
from posthog.test.test_utils import FAKE_TEST_API_KEY
13-
from posthog.version import VERSION
1413
from posthog.types import FeatureFlag, LegacyFlagMetadata
14+
from posthog.version import VERSION
1515

1616

1717
class TestClient(unittest.TestCase):

posthog/test/test_feature_flag.py

Lines changed: 10 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
11
import unittest
2-
from posthog.types import (
3-
FeatureFlag,
4-
FlagMetadata,
5-
FlagReason,
6-
LegacyFlagMetadata,
7-
normalize_decide_response,
8-
to_flags_and_payloads,
9-
)
2+
3+
from posthog.types import FeatureFlag, FlagMetadata, FlagReason, LegacyFlagMetadata
104

115

126
class TestFeatureFlag(unittest.TestCase):
@@ -65,20 +59,14 @@ def test_feature_flag_from_json_without_metadata(self):
6559

6660
def test_flag_reason_from_json(self):
6761
# Test with complete data
68-
resp = {
69-
"code": "user_in_segment",
70-
"condition_index": 1,
71-
"description": "User is in segment 'beta_users'"
72-
}
62+
resp = {"code": "user_in_segment", "condition_index": 1, "description": "User is in segment 'beta_users'"}
7363
reason = FlagReason.from_json(resp)
7464
self.assertEqual(reason.code, "user_in_segment")
7565
self.assertEqual(reason.condition_index, 1)
7666
self.assertEqual(reason.description, "User is in segment 'beta_users'")
7767

7868
# Test with partial data
79-
resp = {
80-
"code": "user_in_segment"
81-
}
69+
resp = {"code": "user_in_segment"}
8270
reason = FlagReason.from_json(resp)
8371
self.assertEqual(reason.code, "user_in_segment")
8472
self.assertEqual(reason.condition_index, 0) # default value
@@ -89,22 +77,15 @@ def test_flag_reason_from_json(self):
8977

9078
def test_flag_metadata_from_json(self):
9179
# Test with complete data
92-
resp = {
93-
"id": 123,
94-
"payload": {"key": "value"},
95-
"version": 1,
96-
"description": "Test flag"
97-
}
80+
resp = {"id": 123, "payload": {"key": "value"}, "version": 1, "description": "Test flag"}
9881
metadata = FlagMetadata.from_json(resp)
9982
self.assertEqual(metadata.id, 123)
10083
self.assertEqual(metadata.payload, {"key": "value"})
10184
self.assertEqual(metadata.version, 1)
10285
self.assertEqual(metadata.description, "Test flag")
10386

10487
# Test with partial data
105-
resp = {
106-
"id": 123
107-
}
88+
resp = {"id": 123}
10889
metadata = FlagMetadata.from_json(resp)
10990
self.assertEqual(metadata.id, 123)
11091
self.assertIsNone(metadata.payload)
@@ -123,14 +104,9 @@ def test_feature_flag_from_json_complete(self):
123104
"reason": {
124105
"code": "user_in_segment",
125106
"condition_index": 1,
126-
"description": "User is in segment 'beta_users'"
107+
"description": "User is in segment 'beta_users'",
127108
},
128-
"metadata": {
129-
"id": 123,
130-
"payload": {"key": "value"},
131-
"version": 1,
132-
"description": "Test flag"
133-
}
109+
"metadata": {"id": 123, "payload": {"key": "value"}, "version": 1, "description": "Test flag"},
134110
}
135111
flag = FeatureFlag.from_json(resp)
136112
self.assertEqual(flag.key, "test-flag")
@@ -144,10 +120,7 @@ def test_feature_flag_from_json_complete(self):
144120

145121
def test_feature_flag_from_json_minimal_data(self):
146122
# Test with minimal data
147-
resp = {
148-
"key": "test-flag",
149-
"enabled": False
150-
}
123+
resp = {"key": "test-flag", "enabled": False}
151124
flag = FeatureFlag.from_json(resp)
152125
self.assertEqual(flag.key, "test-flag")
153126
self.assertFalse(flag.enabled)
@@ -158,13 +131,7 @@ def test_feature_flag_from_json_minimal_data(self):
158131

159132
def test_feature_flag_from_json_with_reason(self):
160133
# Test with reason but no metadata
161-
resp = {
162-
"key": "test-flag",
163-
"enabled": True,
164-
"reason": {
165-
"code": "user_in_segment"
166-
}
167-
}
134+
resp = {"key": "test-flag", "enabled": True, "reason": {"code": "user_in_segment"}}
168135
flag = FeatureFlag.from_json(resp)
169136
self.assertEqual(flag.key, "test-flag")
170137
self.assertTrue(flag.enabled)

posthog/test/test_request.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,13 @@
11
import json
22
import unittest
33
from datetime import date, datetime
4-
from unittest.mock import patch, MagicMock
5-
from parameterized import parameterized
64

75
import mock
86
import pytest
97
import requests
108

11-
from posthog.request import (
12-
DatetimeSerializer,
13-
QuotaLimitError,
14-
batch_post,
15-
decide,
16-
determine_server_host,
17-
)
9+
from posthog.request import DatetimeSerializer, QuotaLimitError, batch_post, decide, determine_server_host
1810
from posthog.test.test_utils import TEST_API_KEY
19-
from posthog.types import FeatureFlag, FlagMetadata, FlagReason, LegacyFlagMetadata
2011

2112

2213
class TestRequests(unittest.TestCase):

posthog/test/test_types.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import unittest
2+
23
from parameterized import parameterized
4+
35
from posthog.types import (
46
FeatureFlag,
57
FlagMetadata,

0 commit comments

Comments
 (0)