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

Use __truediv__ for python2 with __future__ import, refs #11740 #11787

Merged
merged 3 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
9 changes: 7 additions & 2 deletions mypy/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -2188,8 +2188,13 @@ def type_checker(self) -> TypeChecker:
if not self._type_checker:
assert self.tree is not None, "Internal error: must be called on parsed file only"
manager = self.manager
self._type_checker = TypeChecker(manager.errors, manager.modules, self.options,
self.tree, self.xpath, manager.plugin)
self._type_checker = TypeChecker(
manager.errors, manager.modules, self.options,
self.tree, self.xpath, manager.plugin,
self.manager.semantic_analyzer.future_import_flags.get(
self.tree.fullname, set(),
),
)
return self._type_checker

def type_map(self) -> Dict[Expression, Type]:
Expand Down
8 changes: 7 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,12 @@ class TypeChecker(NodeVisitor[None], CheckerPluginInterface):
# functions such as open(), etc.
plugin: Plugin

# Future flags that we get from semantic analyzer for this module.
future_import_flags: Set[str]

def __init__(self, errors: Errors, modules: Dict[str, MypyFile], options: Options,
tree: MypyFile, path: str, plugin: Plugin) -> None:
tree: MypyFile, path: str, plugin: Plugin,
future_import_flags: Set[str]) -> None:
"""Construct a type checker.

Use errors to report type check errors.
Expand Down Expand Up @@ -268,6 +272,8 @@ def __init__(self, errors: Errors, modules: Dict[str, MypyFile], options: Option
# argument through various `checker` and `checkmember` functions.
self._is_final_def = False

self.future_import_flags = future_import_flags

@property
def type_context(self) -> List[Optional[Type]]:
return self.expr_checker.type_context
Expand Down
3 changes: 1 addition & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2414,8 +2414,7 @@ def dangerous_comparison(self, left: Type, right: Type,

def get_operator_method(self, op: str) -> str:
if op == '/' and self.chk.options.python_version[0] == 2:
# TODO also check for "from __future__ import division"
return '__div__'
return '__truediv__' if 'division' in self.chk.future_import_flags else '__div__'
else:
return operators.op_methods[op]

Expand Down
10 changes: 6 additions & 4 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ class SemanticAnalyzer(NodeVisitor[None],
errors: Errors # Keeps track of generated errors
plugin: Plugin # Mypy plugin for special casing of library features
statement: Optional[Statement] = None # Statement/definition being analyzed
future_import_flags: Set[str]
future_import_flags: Dict[str, Set[str]] # Module name / future imports
Copy link
Collaborator

Choose a reason for hiding this comment

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

Could these be stored in MypyFile instead, to avoid two dictionaries keyed with a module name (see modules above)?

Copy link
Member Author

Choose a reason for hiding this comment

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

Done! 👍


# Mapping from 'async def' function definitions to their return type wrapped as a
# 'Coroutine[Any, Any, T]'. Used to keep track of whether a function definition's
Expand Down Expand Up @@ -284,7 +284,7 @@ def __init__(self,
# current SCC or top-level function.
self.deferral_debug_context: List[Tuple[str, int]] = []

self.future_import_flags: Set[str] = set()
self.future_import_flags: Dict[str, Set[str]] = {}

# mypyc doesn't properly handle implementing an abstractproperty
# with a regular attribute so we make them properties
Expand Down Expand Up @@ -5252,10 +5252,12 @@ def parse_bool(self, expr: Expression) -> Optional[bool]:

def set_future_import_flags(self, module_name: str) -> None:
if module_name in FUTURE_IMPORTS:
self.future_import_flags.add(FUTURE_IMPORTS[module_name])
self.future_import_flags.setdefault(
self.cur_mod_id, set(),
).add(FUTURE_IMPORTS[module_name])

def is_future_flag_set(self, flag: str) -> bool:
return flag in self.future_import_flags
return flag in self.future_import_flags.setdefault(self.cur_mod_id, set())


class HasPlaceholders(TypeQuery[bool]):
Expand Down
64 changes: 64 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,70 @@ class C:
pass
[builtins fixtures/tuple.pyi]

[case testDivPython2]
# flags: --python-version 2.7
class A(object):
def __div__(self, other):
# type: (A, str) -> str
return 'a'

a = A()
reveal_type(a / 'b') # N: Revealed type is "builtins.str"
a / 1 # E: Unsupported operand types for / ("A" and "int")
[builtins fixtures/bool.pyi]

[case testDivPython2FutureImport]
# flags: --python-version 2.7
from __future__ import division

class A(object):
def __truediv__(self, other):
# type: (A, str) -> str
return 'a'

a = A()
reveal_type(a / 'b') # N: Revealed type is "builtins.str"
a / 1 # E: Unsupported operand types for / ("A" and "int")
[builtins fixtures/bool.pyi]

[case testDivPython2FutureImportNotLeaking]
# flags: --python-version 2.7
import m1

[file m1.py]
import m2

class A(object):
def __div__(self, other):
# type: (A, str) -> str
return 'a'

a = A()
reveal_type(a / 'b') # N: Revealed type is "builtins.str"
a / 1 # E: Unsupported operand types for / ("A" and "int")
[file m2.py]
from __future__ import division
[builtins fixtures/bool.pyi]

[case testDivPython2FutureImportNotLeaking2]
# flags: --python-version 2.7
import m1

[file m1.py]
import m2

class A(object):
def __div__(self, other):
# type: (A, str) -> str
return 'a'

a = A()
reveal_type(a / 'b') # N: Revealed type is "builtins.str"
a / 1 # E: Unsupported operand types for / ("A" and "int")
[file m2.py]
# empty
[builtins fixtures/bool.pyi]

[case testIntDiv]
a, b, c = None, None, None # type: (A, B, C)
if int():
Expand Down