Skip to content

Commit

Permalink
Add type deduction for type aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
dosisod committed Mar 1, 2024
1 parent 6b9035f commit c30b449
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
8 changes: 7 additions & 1 deletion refurb/checks/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
UnaryExpr,
Var,
)
from mypy.types import AnyType, CallableType, Instance, TupleType, Type
from mypy.types import AnyType, CallableType, Instance, TupleType, Type, TypeAliasType

from refurb import types
from refurb.error import Error
Expand Down Expand Up @@ -572,6 +572,12 @@ def _is_same_type(ty: Type | SymbolNode | None, expected: TypeLike) -> bool:
if ty is expected is None:
return True

if isinstance(ty, TypeAliasType):
if not ty.alias:
return False # pragma: no cover

return _is_same_type(ty.alias.target, expected)

if isinstance(ty, TupleType) and expected is tuple:
return True

Expand Down
8 changes: 8 additions & 0 deletions test/data/type_deduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,13 @@ async def return_bool() -> bool:
_ = bool(cast(bool, 123))


DictAlias = dict[str, str]

# Must use function here so that `d` uses the `DictAlias` type alias. If an intermediate
# object is used the alias will "resolve" and won't trigger the type alias check.
def dict_alias_wrapper(d: DictAlias) -> None:
_ = dict(d)


# These types are not able to be deduced (yet)
_ = int(1 or 2)
1 change: 1 addition & 0 deletions test/data/type_deduce.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ test/data/type_deduce.py:29:5 [FURB123]: Replace `int(+1)` with `+1`
test/data/type_deduce.py:30:5 [FURB123]: Replace `int(~1)` with `~1`
test/data/type_deduce.py:32:5 [FURB123]: Replace `bool(walrus := True)` with `walrus := True`
test/data/type_deduce.py:36:5 [FURB123]: Replace `bool(cast(bool, 123))` with `cast(bool, 123)`
test/data/type_deduce.py:44:9 [FURB123]: Replace `dict(d)` with `d.copy()`

0 comments on commit c30b449

Please sign in to comment.