Python Forum

Full Version: type hint additional message
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm attempting to type hint on a temperature conversion function.
The function has a deliberate mistake in that it returns a Number instead of a dictionary, but the
return statement is for a Dictionary.

#!/home/bluefrog/anaconda3/bin/python3
from decimal import Decimal
from typing import Optional, Union, Dict
Number = Union[int, float, Decimal]

def convert_temperature(*, f_temp: Optional[Number]=None, c_temp: Optional[Number]=None) -> Number:
  if c_temp is None:
    c_temp = 5*(f_temp-32)/9
  elif f_temp is None:
    f_temp = 32+9*c_temp/5
  else:
    raise Exception( "Logic Design Problem" )
    result: Dict[str, Number] = {'c_temp': c_temp,
                                 'f_temp': f_temp}
  return result
When I run mypy I get the expected message on the incorrect return, but I also get 2 other messages that I do not understand:

$ mypy celcius_to_fahrenheit.py 
celcius_to_fahrenheit.py:8: error: Unsupported operand types for - ("None" and "int")
celcius_to_fahrenheit.py:8: note: Left operand is of type "Union[int, float, Decimal, None]"
celcius_to_fahrenheit.py:15: error: Incompatible return value type (got "Dict[str, Union[int, float, Decimal]]", expected "Union[int, float, Decimal]")
Could somebody explain why the 2 messages for line 8 appear. I was only expecting a message for line 15, which does appear. I am using 3.7 along with mypy

Thanks
please post error traceback verbatim
celcius_to_fahrenheit.py:8: error: Unsupported operand types for - ("None" and "int")
celcius_to_fahrenheit.py:8: note: Left operand is of type "Union[int, float, Decimal, None]"
celcius_to_fahrenheit.py:15: error: Incompatible return value type (got "Dict[str, Union[int, float, Decimal
This is the complete output. There is no other output.
What mypy configuration are you using?

https://mypy.readthedocs.io/en/latest/config_file.html
I've created a mypy.ini as suggested in the link you posted:
$ pwd
/home/bluefrog/anaconda3/pkgs/mypy-0.620-py37_0
$ cat > mypy.ini <<EOF
> [mypy]
> python_version = 3.7
> warn_return_any = True
> warn_unused_configs = True
> EOF

$ cd ~/sample_code/python/functions/

$ ~/anaconda3/pkgs/mypy-0.620-py37_0/bin/mypy celcius_to_fahrenheit2.py 
celcius_to_fahrenheit2.py:8: error: Unsupported operand types for - ("Union[int, float, Decimal, None]" and "int")
celcius_to_fahrenheit2.py:15: error: Incompatible return value type (got "Dict[str, Union[int, float, Decimal]]", expected "Union[int, float, Decimal]")
So the first message is now gone, but the second still does not make sense.
Perhaps it is because mypy is still new?
It looks like the minus operator is unsupported because the left hand side may be None, according to the type hints. That's because f_temp is optional. Before trying to use minus with it, you should verify that it is non-None; that should fix your issue.