[Tutor] Type annotation errors

boB Stepp robertvstepp at gmail.com
Wed Jun 3 23:36:30 EDT 2020


I have been continuing to try to understand what is going on.

On Sat, May 30, 2020 at 8:42 PM boB Stepp <robertvstepp at gmail.com> wrote:
>
> The following function yields type annotation errors and I do not
> understand why:
>
> def evaluate_portfolio(
>      portfolio: List[Dict[str, Union[str, int, float]]], stock_prices: Dict[str, float]
> ) -> Tuple[float, float]:
>      """Compute the current value and gain/loss of a portfolio."""
>      portfolio_value = 0.0
>      gain_loss = 0.0
>      for stock in portfolio:
>          current_value = stock["shares"] * stock_prices[stock["name"]]
>          current_gain_loss = current_value - (stock["shares"] * stock["price"])
>          portfolio_value += current_value
>          gain_loss += current_gain_loss
>      return portfolio_value, gain_loss
>
> The error messages generated are:
>
> report.py|47 col 43 info| Left operand is of type "Union[str, int, float]"
> report.py|47 col 43 error| Unsupported operand types for * ("str" and "float")
> report.py|47 col 56 error| Invalid index type "Union[str, int, float]" for "Dict[str, float]"; expected type "str"
> report.py|48 col 29 info| Both left and right operands are unions
> report.py|48 col 29 error| Unsupported operand types for - ("float" and "str")
> report.py|48 col 46 error| Unsupported operand types for * ("str" and "str")
> report.py|48 col 46 error| Unsupported operand types for * ("str" and "float")
> report.py|48 col 46 error| Unsupported operand types for * ("float" and "str")

If I simplify the type annotations to:

def evaluate_portfolio(
    portfolio: List[Dict], stock_prices: Dict[str, float]
) -> Tuple[float, float]:
    """Compute the current value and gain/loss of a portfolio."""
    portfolio_value = 0.0
    gain_loss = 0.0
    for stock in portfolio:
        current_value = stock["shares"] * stock_prices[stock["name"]]
        current_gain_loss = current_value - (stock["shares"] * stock["price"])
        portfolio_value += current_value
        gain_loss += current_gain_loss
    return portfolio_value, gain_loss

Then all of the complaints go away.  I still do not understand why the
more detailed annotations do not give the expected results.  I have
read and reread the documentation multiple times, but I believe I am
doing the annotations correctly.  Perhaps there is a nesting limit
beyond which mypy chokes?

-- 
boB


More information about the Tutor mailing list