Skip to content

Commit

Permalink
Only auto-fix builtin types in UseTypesFromTypingRule (#178)
Browse files Browse the repository at this point in the history
* Only change builtin types in `UseTypesFromTypingRule`

*Problem*

`UseTypesFromTypingRule` incorrectly changed `list` to `List` in
this real-world snippet:

```
from typing import List as list
from graphene import List

def function(a: list[int]) -> List[int]:
    return []
```

*Solution*

Refine the check to confirm the node is a builtin

* formatting
  • Loading branch information
alambert authored Mar 31, 2021
1 parent 6fe8953 commit 623d0d3
Showing 1 changed file with 29 additions and 3 deletions.
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

0 comments on commit 623d0d3

Please sign in to comment.