Search code examples
pythonpandasmypy

How to explicitly tell mypy the correct type of a variable?


I pick a value of a pandas dataframe and the type of the variable is string. In a function I return this value and I have annoted the value as str.

def get_item_name(code: str) -> str:
    item = df.loc[code, "item_name"]
    return item

However, mypy gives me the following warning:

Expression of type "Scalar" cannot be assigned to return type "str"
Type "Scalar" cannot be assigned to type "str" "bytes" is incompatible with "str"PylancereportGeneralTypeIssues

Is there a way to explicitly tell mypy that the correct type of variable item is string?

I get the warning to disappear if I use str(df.loc[code, "item_name"]) but this makes the code look like the value could be a number but we convert it to string, which is not the case as the value is already string.


Solution

  • If you are really sure, you can use cast. You should be careful with this, though.

    from typing import cast
    
    def get_item_name(code: str) -> str:
        item = df.loc[code, "item_name"]
        return cast(str, item)