You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Optional generic not accepted with --strict-optional #2678
When running with --strict-optional, mypy complains about the last statement here. However, this seems like it should work, both because it does work when --strict-optional is left out, and because the revealed type looks like it should match.
fromtypingimportOptional, Type, TypeVarclassBaseThing: passclassChildThing(BaseThing): passThingClass=TypeVar("ThingClass", bound=BaseThing)
defget_thing(thing_class: Type[ThingClass]) ->Optional[ThingClass]:
""" Get the thing with the given class. Stub implementation. """returnNonething=None# type: Optional[ChildThing]# Fails, complaining about `Type argument 1 of "get_thing" has incompatible value "Optional[ChildThing]"`thing=get_thing(ChildThing)
# Revealed type is `Union[scratch_1.ChildThing*, builtins.None]`, which seems like it should # match Optional[ChildThing].reveal_type(get_thing(ChildThing))
Hm, I wonder if the problem is due to a bad interaction between the ThingClass TypeVar and the Optional from the context? I think it ought to infer that if the context is Optional[ChildThing] and the return type (to be matched to that context) is Optional[ThingClass], then it must solve this to ThingClass==ChildThing, but it is then not correctly concluding that the argument type must be Type[ChildThing].
test.py:14: error: Revealed type is 'Union[test.B, builtins.str]'
test.py:15: error: Revealed type is 'Union[test.B*, builtins.str]'
test.py:16: error: Type argument 1 of "f" has incompatible value "Union[B, str]"
We've known for a while that TypeVars and Unions don't play well together. There's been a bit of spot-patching so far, but I think we're at the point where a larger careful rethinking makes sense.
Activity
gvanrossum commentedon Jan 11, 2017
Hm, I wonder if the problem is due to a bad interaction between the ThingClass TypeVar and the Optional from the context? I think it ought to infer that if the context is Optional[ChildThing] and the return type (to be matched to that context) is Optional[ThingClass], then it must solve this to ThingClass==ChildThing, but it is then not correctly concluding that the argument type must be Type[ChildThing].
ddfisher commentedon Jan 11, 2017
This problem isn't Optional-specific -- it'll happen with any Union. For example:
We've known for a while that TypeVars and Unions don't play well together. There's been a bit of spot-patching so far, but I think we're at the point where a larger careful rethinking makes sense.
Improve usage of outer context for inference (#5699)
Improve usage of outer context for inference (python#5699)