Skip to content
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

Only change builtin types in UseTypesFromTypingRule #178

Merged
merged 2 commits into from
Mar 31, 2021
Merged
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
32 changes: 29 additions & 3 deletions fixit/rules/use_types_from_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Set

import libcst
from libcst.metadata import ScopeProvider
from libcst.metadata import QualifiedNameProvider, ScopeProvider

from fixit import (
CstContext,
Expand All @@ -23,6 +23,7 @@
)

BUILTINS_TO_REPLACE: Set[str] = {"dict", "list", "set", "tuple"}
QUALIFIED_BUILTINS_TO_REPLACE: Set[str] = {f"builtins.{s}" for s in BUILTINS_TO_REPLACE}


class UseTypesFromTypingRule(CstLintRule):
Expand All @@ -31,7 +32,10 @@ class UseTypesFromTypingRule(CstLintRule):
since the type system doesn't recognize the latter as a valid type.
"""

METADATA_DEPENDENCIES = (ScopeProvider,)
METADATA_DEPENDENCIES = (
QualifiedNameProvider,
ScopeProvider,
)
VALID = [
Valid(
"""
Expand All @@ -58,6 +62,15 @@ def function() -> bool:
return Dict == List
"""
),
Valid(
"""
from typing import List as list
from graphene import List
def function(a: list[int]) -> List[int]:
return []
"""
),
]
INVALID = [
Invalid(
Expand Down Expand Up @@ -115,7 +128,20 @@ def leave_Annotation(self, original_node: libcst.Annotation) -> None:
self.annotation_counter -= 1

def visit_Name(self, node: libcst.Name) -> None:
if self.annotation_counter > 0 and node.value in BUILTINS_TO_REPLACE:
# Avoid a false-positive in this scenario:
#
# ```
# from typing import List as list
# from graphene import List
# ```
qualified_names = self.get_metadata(QualifiedNameProvider, node, set())

is_builtin_type = node.value in BUILTINS_TO_REPLACE and all(
qualified_name.name in QUALIFIED_BUILTINS_TO_REPLACE
for qualified_name in qualified_names
)

if self.annotation_counter > 0 and is_builtin_type:
correct_type = node.value.title()
scope = self.get_metadata(ScopeProvider, node)
replacement = None
Expand Down