[Tutor] Type annotation errors

boB Stepp robertvstepp at gmail.com
Sat May 30 21:42:08 EDT 2020


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")

For reference line 47 is the line in the for loop beginning
"current_value..."

portfolio is a list of dictionaries where each dictionary is of the form
{"name": "stock name", "shares": number_of_shares_owned, "price":
price_per_share}

The code runs flawlessly and gives the expected results.  Where am I going
wrong in my type annotations?

-- 
Wishing you only the best,

boB Stepp


More information about the Tutor mailing list