Skip to content

Commit

Permalink
chore(types): Remove all unused type ignore comments (#19692)
Browse files Browse the repository at this point in the history
  • Loading branch information
webjunkie authored Jan 10, 2024
1 parent e5bdceb commit d3f230a
Show file tree
Hide file tree
Showing 30 changed files with 117 additions and 126 deletions.
4 changes: 2 additions & 2 deletions ee/api/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ class PublicIntegrationViewSet(viewsets.GenericViewSet):
queryset = Integration.objects.all()
serializer_class = IntegrationSerializer

authentication_classes = [] # type: ignore
permission_classes = [] # type: ignore
authentication_classes = []
permission_classes = []

@action(methods=["POST"], detail=False, url_path="slack/events")
def slack_events(self, request: Request, *args: Any, **kwargs: Any) -> Response:
Expand Down
12 changes: 6 additions & 6 deletions ee/api/test/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class LicensedTestMixin:

CONFIG_LICENSE_KEY: Optional[str] = "12345::67890"
CONFIG_LICENSE_PLAN: Optional[str] = "enterprise"
license: License = None # type: ignore
license: License = None

def license_required_response(
self,
Expand All @@ -30,17 +30,17 @@ def license_required_response(

@classmethod
def setUpTestData(cls):
super().setUpTestData() # type: ignore
super().setUpTestData()
if cls.CONFIG_LICENSE_PLAN:
cls.license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key=cls.CONFIG_LICENSE_KEY,
plan=cls.CONFIG_LICENSE_PLAN,
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7, tzinfo=ZoneInfo("UTC")),
)
if hasattr(cls, "organization") and cls.organization: # type: ignore
cls.organization.available_product_features = AVAILABLE_PRODUCT_FEATURES # type: ignore
cls.organization.update_available_features() # type: ignore
cls.organization.save() # type: ignore
if hasattr(cls, "organization") and cls.organization:
cls.organization.available_product_features = AVAILABLE_PRODUCT_FEATURES
cls.organization.update_available_features()
cls.organization.save()


class APILicensedTest(LicensedTestMixin, APIBaseTest):
Expand Down
91 changes: 41 additions & 50 deletions mypy-baseline.txt

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions posthog/api/feature_flag.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def get_features(self, feature_flag: FeatureFlag) -> Dict:
def get_surveys(self, feature_flag: FeatureFlag) -> Dict:
from posthog.api.survey import SurveyAPISerializer

return SurveyAPISerializer(feature_flag.surveys_linked_flag, many=True).data # type: ignore
return SurveyAPISerializer(feature_flag.surveys_linked_flag, many=True).data
# ignoring type because mypy doesn't know about the surveys_linked_flag `related_name` relationship

def get_rollout_percentage(self, feature_flag: FeatureFlag) -> Optional[int]:
Expand Down Expand Up @@ -180,7 +180,7 @@ def validate_filters(self, filters):
# If we see this, just return the current filters
if "groups" not in filters and self.context["request"].method == "PATCH":
# mypy cannot tell that self.instance is a FeatureFlag
return self.instance.filters # type: ignore
return self.instance.filters

aggregation_group_type_index = filters.get("aggregation_group_type_index", None)

Expand Down
12 changes: 6 additions & 6 deletions posthog/api/person.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.
),
],
)
def destroy(self, request: request.Request, pk=None, **kwargs): # type: ignore
def destroy(self, request: request.Request, pk=None, **kwargs):
try:
person = self.get_object()
person_id = person.id
Expand Down Expand Up @@ -441,7 +441,7 @@ def values(self, request: request.Request, **kwargs) -> response.Response:
# Try loading as json for dicts or arrays
flattened.append(
{
"name": convert_property_value(json.loads(value)), # type: ignore
"name": convert_property_value(json.loads(value)),
"count": count,
}
)
Expand Down Expand Up @@ -481,7 +481,7 @@ def split(self, request: request.Request, pk=None, **kwargs) -> response.Respons
log_activity(
organization_id=self.organization.id,
team_id=self.team.id,
user=request.user, # type: ignore
user=request.user,
item_id=person.id,
scope="Person",
activity="split_person",
Expand Down Expand Up @@ -572,7 +572,7 @@ def delete_property(self, request: request.Request, pk=None, **kwargs) -> respon
log_activity(
organization_id=self.organization.id,
team_id=self.team.id,
user=request.user, # type: ignore
user=request.user,
item_id=person.id,
scope="Person",
activity="delete_property",
Expand Down Expand Up @@ -921,14 +921,14 @@ def prepare_actor_query_filter(filter: T) -> T:
"key": "name",
"value": search,
"type": "group",
"group_type_index": filter.aggregation_group_type_index, # type: ignore
"group_type_index": filter.aggregation_group_type_index,
"operator": "icontains",
},
{
"key": "slug",
"value": search,
"type": "group",
"group_type_index": filter.aggregation_group_type_index, # type: ignore
"group_type_index": filter.aggregation_group_type_index,
"operator": "icontains",
},
]
Expand Down
20 changes: 10 additions & 10 deletions posthog/api/property_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,13 +468,13 @@ def get_queryset(self):

property_definition_fields = ", ".join(
[
f'posthog_propertydefinition."{f.column}"' # type: ignore
f'posthog_propertydefinition."{f.column}"'
for f in PropertyDefinition._meta.get_fields()
if hasattr(f, "column")
]
)

use_enterprise_taxonomy = self.request.user.organization.is_feature_available( # type: ignore
use_enterprise_taxonomy = self.request.user.organization.is_feature_available(
AvailableFeature.INGESTION_TAXONOMY
)
order_by_verified = False
Expand All @@ -485,9 +485,9 @@ def get_queryset(self):
# Prevent fetching deprecated `tags` field. Tags are separately fetched in TaggedItemSerializerMixin
property_definition_fields = ", ".join(
[
f'{f.cached_col.alias}."{f.column}"' # type: ignore
f'{f.cached_col.alias}."{f.column}"'
for f in EnterprisePropertyDefinition._meta.get_fields()
if hasattr(f, "column") and f.column not in ["deprecated_tags", "tags"] # type: ignore
if hasattr(f, "column") and f.column not in ["deprecated_tags", "tags"]
]
)

Expand All @@ -502,8 +502,8 @@ def get_queryset(self):
except ImportError:
use_enterprise_taxonomy = False

limit = self.paginator.get_limit(self.request) # type: ignore
offset = self.paginator.get_offset(self.request) # type: ignore
limit = self.paginator.get_limit(self.request)
offset = self.paginator.get_offset(self.request)

query = PropertyDefinitionQuerySerializer(data=self.request.query_params)
query.is_valid(raise_exception=True)
Expand Down Expand Up @@ -547,26 +547,26 @@ def get_queryset(self):
cursor.execute(query_context.as_count_sql(), query_context.params)
full_count = cursor.fetchone()[0]

self.paginator.set_count(full_count) # type: ignore
self.paginator.set_count(full_count)

return queryset.raw(query_context.as_sql(order_by_verified), params=query_context.params)

def get_serializer_class(self) -> Type[serializers.ModelSerializer]:
serializer_class = self.serializer_class
if self.request.user.organization.is_feature_available(AvailableFeature.INGESTION_TAXONOMY): # type: ignore
if self.request.user.organization.is_feature_available(AvailableFeature.INGESTION_TAXONOMY):
try:
from ee.api.ee_property_definition import (
EnterprisePropertyDefinitionSerializer,
)
except ImportError:
pass
else:
serializer_class = EnterprisePropertyDefinitionSerializer # type: ignore
serializer_class = EnterprisePropertyDefinitionSerializer
return serializer_class

def get_object(self):
id = self.kwargs["id"]
if self.request.user.organization.is_feature_available(AvailableFeature.INGESTION_TAXONOMY): # type: ignore
if self.request.user.organization.is_feature_available(AvailableFeature.INGESTION_TAXONOMY):
try:
from ee.models.property_definition import EnterprisePropertyDefinition
except ImportError:
Expand Down
4 changes: 2 additions & 2 deletions posthog/api/sharing.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,8 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, StructuredViewSetMixin
4. Export downloading - used to download the actual content of an export if requested with the correct extension
"""

authentication_classes = [] # type: ignore
permission_classes = [] # type: ignore
authentication_classes = []
permission_classes = []
include_in_docs = False

def get_object(self) -> Optional[SharingConfiguration | ExportedAsset]:
Expand Down
2 changes: 1 addition & 1 deletion posthog/api/test/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,7 @@ def test_batch(self, kafka_produce):
"distinct_id": "2",
"ip": "127.0.0.1",
"site_url": "http://testserver",
"data": {**data, "properties": {}}, # type: ignore
"data": {**data, "properties": {}},
"token": self.team.api_token,
},
)
Expand Down
4 changes: 2 additions & 2 deletions posthog/api/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def get_is_impersonated(self, _) -> Optional[bool]:
return is_impersonated_session(self.context["request"])

def get_has_social_auth(self, instance: User) -> bool:
return instance.social_auth.exists() # type: ignore
return instance.social_auth.exists()

def get_is_2fa_enabled(self, instance: User) -> bool:
return default_device(instance) is not None
Expand Down Expand Up @@ -167,7 +167,7 @@ def validate_notification_settings(self, notification_settings: Notifications) -
raise serializers.ValidationError(
f"{value} is not a valid type for notification settings, should be {Notifications.__annotations__[key]}"
)
return {**NOTIFICATION_DEFAULTS, **notification_settings} # type: ignore
return {**NOTIFICATION_DEFAULTS, **notification_settings}

def validate_password_change(
self, instance: User, current_password: Optional[str], password: Optional[str]
Expand Down
8 changes: 4 additions & 4 deletions posthog/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,12 +257,12 @@ def create_event_definitions_sql(

ee_model = EnterpriseEventDefinition
else:
ee_model = EventDefinition # type: ignore
ee_model = EventDefinition

event_definition_fields = {
f'"{f.column}"' # type: ignore
f'"{f.column}"'
for f in ee_model._meta.get_fields()
if hasattr(f, "column") and f.column not in ["deprecated_tags", "tags"] # type: ignore
if hasattr(f, "column") and f.column not in ["deprecated_tags", "tags"]
}

enterprise_join = (
Expand Down Expand Up @@ -296,7 +296,7 @@ def create_event_definitions_sql(
def get_pk_or_uuid(queryset: QuerySet, key: Union[int, str]) -> QuerySet:
try:
# Test if value is a UUID
UUID(key) # type: ignore
UUID(key)
return queryset.filter(uuid=key)
except ValueError:
return queryset.filter(pk=key)
Expand Down
2 changes: 1 addition & 1 deletion posthog/batch_exports/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def validate_date_input(date_input: Any) -> dt.datetime:
# As far as I'm concerned, if you give me something that quacks like an isoformatted str, you are golden.
# Read more here: https://github.com/python/mypy/issues/2420.
# Once PostHog is 3.11, try/except is zero cost if nothing is raised: https://bugs.python.org/issue40222.
parsed = dt.datetime.fromisoformat(date_input.replace("Z", "+00:00")) # type: ignore
parsed = dt.datetime.fromisoformat(date_input.replace("Z", "+00:00"))
except (TypeError, ValueError):
raise ValidationError(f"Input {date_input} is not a valid ISO formatted datetime.")
return parsed
Expand Down
4 changes: 2 additions & 2 deletions posthog/hogql_queries/query_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def get_query_runner(
if isinstance(query, dict):
kind = query.get("kind", None)
elif hasattr(query, "kind"):
kind = query.kind # type: ignore
kind = query.kind
else:
raise ValueError(f"Can't get a runner for an unknown query type: {query}")

Expand Down Expand Up @@ -232,7 +232,7 @@ def __init__(
self.limit_context = limit_context or LimitContext.QUERY
self.modifiers = create_default_modifiers_for_team(team, modifiers)
if isinstance(query, self.query_type):
self.query = query # type: ignore
self.query = query
else:
self.query = self.query_type.model_validate(query)

Expand Down
20 changes: 10 additions & 10 deletions posthog/hogql_queries/test/test_query_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class TestQuery(BaseModel):


class TestQueryRunner(BaseTest):
def setup_test_query_runner_class(self, query_class: Type[RunnableQueryNode] = TestQuery): # type: ignore
def setup_test_query_runner_class(self, query_class: Type[RunnableQueryNode] = TestQuery):
"""Setup required methods and attributes of the abstract base class."""

class TestQueryRunner(QueryRunner):
Expand All @@ -47,21 +47,21 @@ def _is_stale(self, cached_result_package) -> bool:
def test_init_with_query_instance(self):
TestQueryRunner = self.setup_test_query_runner_class()

runner = TestQueryRunner(query=TestQuery(some_attr="bla"), team=self.team) # type: ignore
runner = TestQueryRunner(query=TestQuery(some_attr="bla"), team=self.team)

self.assertEqual(runner.query, TestQuery(some_attr="bla"))

def test_init_with_query_dict(self):
TestQueryRunner = self.setup_test_query_runner_class()

runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team) # type: ignore
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)

self.assertEqual(runner.query, TestQuery(some_attr="bla"))

def test_serializes_to_json(self):
TestQueryRunner = self.setup_test_query_runner_class()

runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team) # type: ignore
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)

json = runner.toJSON()
self.assertEqual(json, '{"some_attr":"bla"}')
Expand All @@ -80,7 +80,7 @@ def test_serializes_to_json_ignores_empty_dict(self):
# implement custom validators for this.
TestQueryRunner = self.setup_test_query_runner_class()

runner = TestQueryRunner(query={"some_attr": "bla", "other_attr": []}, team=self.team) # type: ignore
runner = TestQueryRunner(query={"some_attr": "bla", "other_attr": []}, team=self.team)

json = runner.toJSON()
self.assertEqual(json, '{"some_attr":"bla"}')
Expand All @@ -90,21 +90,21 @@ def test_cache_key(self):
# set the pk directly as it affects the hash in the _cache_key call
team = Team.objects.create(pk=42, organization=self.organization)

runner = TestQueryRunner(query={"some_attr": "bla"}, team=team) # type: ignore
runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)

cache_key = runner._cache_key()
self.assertEqual(cache_key, "cache_b8a6b70478ec6139c8f7f379c808d5b9")

def test_cache_key_runner_subclass(self):
TestQueryRunner = self.setup_test_query_runner_class()

class TestSubclassQueryRunner(TestQueryRunner): # type: ignore
class TestSubclassQueryRunner(TestQueryRunner):
pass

# set the pk directly as it affects the hash in the _cache_key call
team = Team.objects.create(pk=42, organization=self.organization)

runner = TestSubclassQueryRunner(query={"some_attr": "bla"}, team=team) # type: ignore
runner = TestSubclassQueryRunner(query={"some_attr": "bla"}, team=team)

cache_key = runner._cache_key()
self.assertEqual(cache_key, "cache_cfab9e42d088def74792922de5b513ac")
Expand All @@ -115,15 +115,15 @@ def test_cache_key_different_timezone(self):
team.timezone = "Europe/Vienna"
team.save()

runner = TestQueryRunner(query={"some_attr": "bla"}, team=team) # type: ignore
runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)

cache_key = runner._cache_key()
self.assertEqual(cache_key, "cache_9f12fefe07c0ab79e93935aed6b0bfa6")

def test_cache_response(self):
TestQueryRunner = self.setup_test_query_runner_class()

runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team) # type: ignore
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)

with freeze_time(datetime(2023, 2, 4, 13, 37, 42)):
# returns fresh response if uncached
Expand Down
2 changes: 1 addition & 1 deletion posthog/migrations/0034_pg_trgm_and_btree_20200318_1447.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ class Migration(migrations.Migration):
]

# We used to install TrigramExtension and BtreeGinExtension, but realised that made things slower rather than faster
operations = [] # type: ignore
operations = []
2 changes: 1 addition & 1 deletion posthog/migrations/0041_merge_20200407_1805.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ class Migration(migrations.Migration):
("posthog", "0039_user_email_opt_in"),
]

operations = [] # type: ignore
operations = []
2 changes: 1 addition & 1 deletion posthog/migrations/0117_merge_20210126_0917.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ class Migration(migrations.Migration):
("posthog", "0116_session_recording_retention_period"),
]

operations = [] # type: ignore
operations = []
2 changes: 1 addition & 1 deletion posthog/migrations/0129_merge_20210223_0757.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ class Migration(migrations.Migration):
("posthog", "0127_add_dashboard_filters"),
]

operations = [] # type: ignore
operations = []
2 changes: 1 addition & 1 deletion posthog/migrations/0148_merge_20210506_0823.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ class Migration(migrations.Migration):
("posthog", "0147_fix_stickiness_dashboard_items"),
]

operations = [] # type: ignore
operations = []
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ class Migration(migrations.Migration):
]

# Superseded by 0175_should_update_person_props
operations = [] # type: ignore
operations = []
Loading

0 comments on commit d3f230a

Please sign in to comment.