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
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:
objecttest {
deff:String="test"vals:Option[String] = f
}
which scalac complains about:
error: type mismatch;
found : String
required: Option[String]
val s: Option[String] = f
^
The text was updated successfully, but these errors were encountered:
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.)
Currently mypy does not complain if a function which returns a non-Optional is assigned to a variable annotated as
Optional
:Since it expects
s
to beNone
orstr
, ands
will be astr
, no error is given:However, in a typed system, I would expect it to complain since the return type of
f
does not match the expected type ofs
. It returns astr
which does not match the typeOptional[str]
. The output I would expect would beerror: 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:which scalac complains about:
The text was updated successfully, but these errors were encountered: