[Tutor] Type annotation errors

boB Stepp robertvstepp at gmail.com
Thu Jun 4 20:34:36 EDT 2020


On Thu, Jun 04, 2020 at 03:46:51PM +0200, Peter Otten wrote:
>boB Stepp wrote:

>There might be a way to tell mypy that two cases cannot occur and still use
>dicts as pseudo-structs, but I expect that there will be a big impact of
>optional typing on the design, and unlike unit tests it will not just
>improve the structure, it will also make the code less flexible.
>Replacing the somewhat amorphous dict with a dataclass:
>
>Money = float  # fixme
>
>@dataclass
>class Record:
>    shares: int
>    name: str
>    price: Money
>
>
>def evaluate_portfolio(
>        portfolio: List[Record],
>        stock_prices: Dict[str, Money]
>) -> 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
>
>PS: In spite of my defeatist remark above I prefer this version over the one
>you posted; maybe not all is lost in Python land ;)

In terms of following along with Beazley's course material this would be
cheating.  Classes have not been presented yet.  Even very simple ones.
~(:>))

>PPS: For someone who knows a little C the obvious fix for your version is to
>cast the union to the expected type:
>
>    for stock in portfolio:
>         shares = cast(int, stock["shares"])
>         name = cast(str, stock["name"])
>         price = cast(float, stock["price"])
>
>         current_value =  shares * stock_prices[name]
>         current_gain_loss = current_value - shares * price
>         portfolio_value += current_value
>         gain_loss += current_gain_loss

I saw cast() in the mypy documentation, but had hopes that the problem was
me and my lack of understanding.

-- 
Wishing you only the best,

boB Stepp


More information about the Tutor mailing list