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

Error not reported when using an intermediate variable #5340

Closed
pbasista opened this issue Jul 10, 2018 · 1 comment
Closed

Error not reported when using an intermediate variable #5340

pbasista opened this issue Jul 10, 2018 · 1 comment

Comments

@pbasista
Copy link

I do not understand mypy's behavior on the below code. It reports an error when a certain function call is part of the return statement, but not when the same function call is separated from the return statement by an intermediate variable.

It might be a bug, but also a valid behavior which is just unclear to me.

from typing import Optional, Type, TypeVar

class Custom:
    pass

# when the bound is removed, mypy reports no error
T = TypeVar('T', bound=Custom)

def a(cls: Type[T]) -> Optional[T]:
    return cls()

def b(cls: Type[T]) -> Optional[T]:
    # the return statement triggers the following mypy error:
    # Value of type variable "T" of "a" cannot be "Optional[T]"
    return a(cls)

def c(cls: Type[T]) -> Optional[T]:
    tmp = a(cls)
    # when an intermediate variable is used, no error is reported
    return tmp

The actual behavior is that the error Value of type variable "T" of "a" cannot be "Optional[T]" is reported on the return statement in function b, but not in function c.

I would expect that either the same error was reported both in function b and c or that no error was reported at all. The current behavior seems inconsistent to me. Moreover, I do not understand the root cause of the reported problem.

$ mypy --version
mypy 0.610
$ python3 --version
Python 3.6.6

Q: Do you see the same issue after installing mypy from Git master?
A: Yes, the behavior is the same with mypy 0.620+dev-bc0b551d8df2baadc44f0c3b0b801fcc12119658.

Q: What are the mypy flags you are using? (For example --strict-optional)
A: no flags and no configuration files, simply running mypy script.py

@ilevkivskyi
Copy link
Member

This is yet another duplicate of #4872. The error for b is a false positive, and using a temporary variable is the current workaround. Thanks for reporting!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants