14

One of the new features in Python 3.5 is type-hinting, inspired by mypy.

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 have expected an error, as I am expecting a bool as the return type. 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?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
svenhornberg
  • 14,376
  • 9
  • 40
  • 56

2 Answers2

17

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

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
6

In order to get static checks, consider a project like mypy, on which PEP 484 was based on.

No checking will be performed on runtime is explicitly declared in the PEP to ease fears of some transition to a static looking Python.


As Daniel pointed out, you can view the attributes in the __annotations__ attribute in a form of:

{'return': bool}

for function overdrawn().

If you want you can create your own small type checking function to perform little runtime checks utilizing this dict. Play around with it. Additionally, if you're up for the read, take a look at my answer on type hints here.

Community
  • 1
  • 1
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253