I have the following function:
import pandas as pd
def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
return left == right
I get the following error when I run it through Mypy:
error: Returning Any from function declared to return "bool"
I believe this is because Mypy doesn't know about pd.Timestamp
so treats it as Any
. (Using the Mypy reveal_type
function shows that Mypy treats left
and right
as Any
.)
What is the correct way to deal with this to stop Mypy complaining?
You can use a special comment # type: ignore[code, ...] to only ignore errors with a specific error code (or codes) on a particular line. This can be used even if you have not configured mypy to show error codes. Currently it's only possible to disable arbitrary error codes on individual lines using this comment.
Incremental mode By default, mypy will store type information into a cache. Mypy will use this information to avoid unnecessary recomputation when it type checks your code again. This can help speed up the type checking process, especially when most parts of your program have not changed since the previous mypy run.
(Note that in Python, None is not an empty reference but an object of type None .) In this example mypy will go on to check the last line and report an error, since mypy thinks that the condition could be either True or False: If you use the --warn-unreachable flag, mypy will generate an error about each unreachable code block.
Asks mypy to type check the provided string as a program. A regular expression that matches file names, directory names and paths which mypy should ignore while recursively discovering files to check. Use forward slashes on all platforms. For instance, to avoid discovering any files named setup.py you could pass --exclude '/setup\.py$'.
Starting from mypy 0.600, mypy uses strict optional checking by default, and the None value is not compatible with non-optional types. It’s easy to switch back to the older behavior where None was compatible with arbitrary types (see Disabling strict optional checking ).
By default, mypy allows always-false comparisons like 42 == 'no' . Use this flag to prohibit such comparisons of non-overlapping types, and similar identity and container checks:
you can cast it as a bool.
import pandas as pd
def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
return bool(left == right)
if mypy doesn't like that you can import cast
from typing and use that to cast it to a bool.
import pandas as pd
from typing import cast
def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
result = bool(left == right)
return cast(bool, result)
I have tested it also without using the cast
command. The Mypy check is passed without any error with the following code:
import pandas as pd
def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
return bool(left == right)
(Tested with Mypy 0910.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With