svenhornberg svenhornberg - 9 days ago 8
Python Question

Python 3.5 type hinting does not result in an error

One of the new features in python 3.5 is type hinting inspired from this project.


typing: PEP 484 – Type Hints.


I want to test it, but it does not work as expected.

import typing

class BankAccount:
def __init__(self, initial_balance: int = 0) -> None:
self.balance = initial_balance
def deposit(self, amount: int) -> None:
self.balance += amount
def withdraw(self, amount: int) -> None:
self.balance -= amount
def overdrawn(self) -> bool:
return str(self.balance < 0)

my_account = BankAccount(15)
my_account.withdraw(5)
print(type(my_account.overdrawn()))


results in:

<class 'str'>


I would expect an error because I am expecting a bool as return. I tested it on python:3.5 (docker) and local. Did i miss something, to make it work? Does this typing not work at runtime (like python app.py)?

Answer

See the fifth paragraph of the abstract in the PEP you link to:

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime . Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily

Comments