Skip to content

Treat non-inplace augmented assignment as a simple assignment #3110

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

Merged
merged 4 commits into from
May 22, 2017
Merged
Show file tree
Hide file tree
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
16 changes: 10 additions & 6 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1939,14 +1939,18 @@ def visit_operator_assignment_stmt(self,
"""Type check an operator assignment statement, e.g. x += 1."""
lvalue_type = self.expr_checker.accept(s.lvalue)
inplace, method = infer_operator_assignment_method(lvalue_type, s.op)
rvalue_type, method_type = self.expr_checker.check_op(
method, lvalue_type, s.rvalue, s)

if isinstance(s.lvalue, IndexExpr) and not inplace:
self.check_indexed_assignment(s.lvalue, s.rvalue, s.rvalue)
else:
if inplace:
# There is __ifoo__, treat as x = x.__ifoo__(y)
rvalue_type, method_type = self.expr_checker.check_op(
method, lvalue_type, s.rvalue, s)
if not is_subtype(rvalue_type, lvalue_type):
self.msg.incompatible_operator_assignment(s.op, s)
else:
# There is no __ifoo__, treat as x = x <foo> y
expr = OpExpr(s.op, s.lvalue, s.rvalue)
expr.set_line(s)
self.check_assignment(lvalue=s.lvalue, rvalue=expr,
infer_lvalue_type=True, new_syntax=False)

def visit_assert_stmt(self, s: AssertStmt) -> None:
self.expr_checker.accept(s.expr)
Expand Down
1 change: 0 additions & 1 deletion test-data/unit/check-generics.test
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,6 @@ class C:
def __add__(self, o: 'C') -> 'C': pass
[out]
main:7: error: Unsupported operand types for + ("C" and "B")
main:7: error: Incompatible types in assignment (expression has type "B", target has type "C")
main:8: error: Invalid index type "C" for A[C]; expected type "B"

[case testOperatorAssignmentWithIndexLvalue2]
Expand Down
47 changes: 45 additions & 2 deletions test-data/unit/check-statements.test
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ class B:
class C: pass
[out]
main:3: error: Unsupported operand types for + ("A" and "B")
main:4: error: Result type of + incompatible in assignment
main:4: error: Incompatible types in assignment (expression has type "C", variable has type "B")
main:5: error: Unsupported left operand type for + ("C")

[case testMinusAssign]
Expand All @@ -246,7 +246,7 @@ class B:
class C: pass
[out]
main:3: error: Unsupported operand types for - ("A" and "B")
main:4: error: Result type of - incompatible in assignment
main:4: error: Incompatible types in assignment (expression has type "C", variable has type "B")
main:5: error: Unsupported left operand type for - ("C")

[case testMulAssign]
Expand Down Expand Up @@ -1514,3 +1514,46 @@ class A(): pass
class B(): pass
[out]
main:8: error: Incompatible types in assignment (expression has type "A", variable has type "B")

[case testAugmentedAssignmentIntFloat]
weight0 = 65.5
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add reveal_type(weight0) after each assignment.

Copy link
Contributor Author

@pkch pkch Apr 4, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After I did it, I discovered another problem: I didn't update the binder (the last weight0 should go back to float, but it stayed as int in my patch). I have fixed it by using a higher level check_assignment method instead of copying/pasting a line from check_simple_assignment . I think this way, the code has become cleaner overall since I could get rid of a couple lines from the original implementation of visit_operator_assignment_stmt (they are taken care of in the check_assignment call).

reveal_type(weight0) # E: Revealed type is 'builtins.float'
weight0 = 65
reveal_type(weight0) # E: Revealed type is 'builtins.int'
weight0 *= 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "float")
weight0 *= 0.5
reveal_type(weight0) # E: Revealed type is 'builtins.float'
weight0 *= object() # E: Unsupported operand types for * ("float" and "object")
reveal_type(weight0) # E: Revealed type is 'builtins.float'

[builtins fixtures/float.pyi]

[case testAugmentedAssignmentIntFloatMember]
class A:
def __init__(self) -> None:
self.weight0 = 65.5
reveal_type(self.weight0) # E: Revealed type is 'builtins.float'
self.weight0 = 65
reveal_type(self.weight0) # E: Revealed type is 'builtins.int'
self.weight0 *= 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "float")
self.weight0 *= 0.5
reveal_type(self.weight0) # E: Revealed type is 'builtins.float'
self.weight0 *= object() # E: Unsupported operand types for * ("float" and "object")
reveal_type(self.weight0) # E: Revealed type is 'builtins.float'

[builtins fixtures/float.pyi]

[case testAugmentedAssignmentIntFloatDict]
from typing import Dict
d = {'weight0': 65.5}
reveal_type(d['weight0']) # E: Revealed type is 'builtins.float*'
d['weight0'] = 65
reveal_type(d['weight0']) # E: Revealed type is 'builtins.float*'
d['weight0'] *= 'a' # E: Unsupported operand types for * ("float" and "str") # E: Incompatible types in assignment (expression has type "str", target has type "float")
d['weight0'] *= 0.5
reveal_type(d['weight0']) # E: Revealed type is 'builtins.float*'
d['weight0'] *= object() # E: Unsupported operand types for * ("float" and "object")
reveal_type(d['weight0']) # E: Revealed type is 'builtins.float*'

[builtins fixtures/floatdict.pyi]

31 changes: 31 additions & 0 deletions test-data/unit/fixtures/float.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Any = 0

class object:
def __init__(self) -> None: pass

class type:
def __init__(self, x: Any) -> None: pass

class str:
def __add__(self, other: 'str') -> 'str': pass
def __rmul__(self, n: int) -> str: ...

class bytes: pass

class tuple: pass
class function: pass

class ellipsis: pass


class int:
def __float__(self) -> float: ...
def __int__(self) -> int: ...
def __mul__(self, x: int) -> int: ...
def __rmul__(self, x: int) -> int: ...

class float:
def __float__(self) -> float: ...
def __int__(self) -> int: ...
def __mul__(self, x: float) -> float: ...
def __rmul__(self, x: float) -> float: ...
63 changes: 63 additions & 0 deletions test-data/unit/fixtures/floatdict.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from typing import TypeVar, Generic, Iterable, Iterator, Mapping, Tuple, overload, Optional, Union

T = TypeVar('T')
KT = TypeVar('KT')
VT = TypeVar('VT')

Any = 0

class object:
def __init__(self) -> None: pass

class type:
def __init__(self, x: Any) -> None: pass

class str:
def __add__(self, other: 'str') -> 'str': pass
def __rmul__(self, n: int) -> str: ...

class bytes: pass

class tuple: pass
class function: pass

class ellipsis: pass

class list(Iterable[T], Generic[T]):
@overload
def __init__(self) -> None: pass
@overload
def __init__(self, x: Iterable[T]) -> None: pass
def __iter__(self) -> Iterator[T]: pass
def __add__(self, x: list[T]) -> list[T]: pass
def __mul__(self, x: int) -> list[T]: pass
def __getitem__(self, x: int) -> T: pass
def append(self, x: T) -> None: pass
def extend(self, x: Iterable[T]) -> None: pass

class dict(Iterable[KT], Mapping[KT, VT], Generic[KT, VT]):
@overload
def __init__(self, **kwargs: VT) -> None: pass
@overload
def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass
def __setitem__(self, k: KT, v: VT) -> None: pass
def __getitem__(self, k: KT) -> VT: pass
def __iter__(self) -> Iterator[KT]: pass
def update(self, a: Mapping[KT, VT]) -> None: pass
@overload
def get(self, k: KT) -> Optional[VT]: pass
@overload
def get(self, k: KT, default: Union[KT, T]) -> Union[VT, T]: pass


class int:
def __float__(self) -> float: ...
def __int__(self) -> int: ...
def __mul__(self, x: int) -> int: ...
def __rmul__(self, x: int) -> int: ...

class float:
def __float__(self) -> float: ...
def __int__(self) -> int: ...
def __mul__(self, x: float) -> float: ...
def __rmul__(self, x: float) -> float: ...