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

Typechecking of variables annotated as Optional against functions not returning Optional #2512

Closed
Saityi opened this issue Nov 30, 2016 · 1 comment
Labels

Comments

@Saityi
Copy link

Saityi commented Nov 30, 2016

Currently mypy does not complain if a function which returns a non-Optional is assigned to a variable annotated as Optional:

from typing import Optional

def f() -> str:
  return 'test'

s = f() # type: Optional[str]

Since it expects s to be None or str, and s will be a str, no error is given:

$ mypy test.py
$

However, in a typed system, I would expect it to complain since the return type of f does not match the expected type of s. It returns a str which does not match the type Optional[str]. The output I would expect would be error: Incompatible types in assignment (expression has type "str", variable has type "Optional[str]" -- similar to of the types of response from type-checking in other languages:

object test {
  def f: String = "test"
  val s: Option[String] = f
}

which scalac complains about:

error: type mismatch;
 found   : String
 required: Option[String]
  val s: Option[String] = f
                          ^
@rwbarton
Copy link
Contributor

In mypy Optional[T] is a supertype of T, the union of T and the type of None. It's not a separate algebraic data type like Haskell's Maybe or, I guess, Scala's Option, where you need a data constructor (Just/Some) to convert from T to Optional[T]. There is no equivalent of this data constructor at runtime in Python, so it doesn't make sense to take the ADT approach. (You could define your own Option class, if you really wanted to.)

(Also, if you don't use --strict-optional, then all types are considered to contain None, so Optional[T] is the same as T. But even with --strict-optional the assignment of str to Optional[str] is valid.)

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

No branches or pull requests

2 participants