-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Mypy should be careful when using outer context for inference #4872
Comments
I set priority to high because I encountered this twice recently. If there is no simple solution we can downgrade to normal. |
A fix might be easy enough -- if the type inferred from the outer context is not compatible with type variable bounds, we leave the value of the type variable indeterminate (similar to what happens if there's no outer context) and continue type checking. Another idea would be to remove union items not compatible with the bound from the inferred type variable value, and to map generic types not compatible with the band down to the bound, if possible. This idea feels a bit ad hoc though. I don't remember ever encountering this issue though. |
#5049 Shows the same problem with unbound type variables which may be harder to fix, because in that case |
Hi, I believe I have the same problem. Please find below another example to replicate. import unittest
from typing import Optional, Type, TypeVar
class A:
def __init__(self) -> None:
print("A: Constructing...")
class B:
def __init__(self) -> None:
print("B: Constructing...")
def do_something(self) -> None:
print("B: Doing something")
class Experimental(object):
T = TypeVar('T', 'A', 'B')
def create_component_a(self) -> Optional['A']:
return self.create_component(A)
# error: Value of type variable "T" of "create_component" of
# "Experimental" cannot be "Optional[A]
def create_component(self, cls: Type[T]) -> Optional[T]:
result = cls()
if hasattr(result, "do_something"):
getattr(result, "do_something")()
return result
class TestFllImporter(unittest.TestCase):
def test_experimental(self) -> None:
optional_a: Optional[A] = None
reveal_type(optional_a)
# error: Revealed type is 'Union[tests.test_experimental.A, None]'
a = A()
reveal_type(a)
# error: Revealed type is 'tests.test_experimental.A'
constructed_a = Experimental().create_component_a()
reveal_type(constructed_a)
# error: Revealed type is 'Union[tests.test_experimental.A, None]'
component_a = Experimental().create_component(A)
reveal_type(component_a)
# error: Revealed type is 'Union[tests.test_experimental.A*, None]'
if __name__ == '__main__':
unittest.main() Any thoughts? Btw, what does the * in Thanks! |
Star means "inferred" (in contrast to explicitly declared). |
On request of @ilevkivskyi, after discussed this on python/typing - Gitter, another example: # pylint: disable=missing-docstring
import re
from typing import Text, Iterable
def get_words(text: Text) -> Iterable[Text]:
return (word.lower() for word in filter(None, re.split(r'\W+', text)))
assert list(get_words("Ham, Spam, Eggs!")) == ['ham', 'spam', 'eggs'] This results in: ../../Library/Preferences/PyCharm2018.2/scratches/try_filter_on_none.py:6: error: Value of type variable "AnyStr" of "split" cannot be "Optional[str]" The workarounds discovered so far are:
(mypy 0.620, Python 3.7.0) |
Fixes #4872 Fixes #3876 Fixes #2678 Fixes #5199 Fixes #5493 (It also fixes a bunch of similar issues previously closed as duplicates, except one, see below). This PR fixes a problems when mypy commits to soon to using outer context for type inference. This is done by: * Postponing inference to inner (argument) context in situations where type inferred from outer (return) context doesn't satisfy bounds or constraints. * Adding a special case for situation where optional return is inferred against optional context. In such situation, unwrapping the optional is a better idea in 99% of cases. (Note: this doesn't affect type safety, only gives empirically more reasonable inferred types.) In general, instead of adding a special case, it would be better to use inner and outer context at the same time, but this a big change (see comment in code), and using the simple special case fixes majority of issues. Among reported issues, only #5311 will stay unfixed.
Fixes python#4872 Fixes python#3876 Fixes python#2678 Fixes python#5199 Fixes python#5493 (It also fixes a bunch of similar issues previously closed as duplicates, except one, see below). This PR fixes a problems when mypy commits to soon to using outer context for type inference. This is done by: * Postponing inference to inner (argument) context in situations where type inferred from outer (return) context doesn't satisfy bounds or constraints. * Adding a special case for situation where optional return is inferred against optional context. In such situation, unwrapping the optional is a better idea in 99% of cases. (Note: this doesn't affect type safety, only gives empirically more reasonable inferred types.) In general, instead of adding a special case, it would be better to use inner and outer context at the same time, but this a big change (see comment in code), and using the simple special case fixes majority of issues. Among reported issues, only python#5311 will stay unfixed.
There are several scenarios, when mypy inference leads to false positives. Namely, if the outer type context (return context) is too wide, mypy uses it and fails immediately. Instead it should try the inner context (argument context) before giving up. For example:
There are similar scenarios with union types, for example:
etc. What is interesting, the failure doesn't happen if there are only simple types present in the bound and in the context, to reproduce one needs either generics, union types, or other "complex" types.
The text was updated successfully, but these errors were encountered: