Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type checking not working as expected

I'm sure I'm missing something obvious here, but why does the following script actually work?

import enum
import typing

class States(enum.Enum):
    a = 1
    b = 2

states = typing.NewType('states', States)

def f(x: states) -> states:
    return x

print(
    f(States.b),
    f(3)
)

As far I understand it, it should fail on the call f(3), however it doesn't. Can someone shed some light on this behaviour?

like image 479
lafras Avatar asked Sep 12 '25 10:09

lafras


1 Answers

No checking is performed by Python itself. This is specified in the "Non- Goals" section of PEP 484. When executed (i.e during run-time), Python completely ignores the annotations you provided and evaluates your statements as it usually does, dynamically.

If you need type checking, you should perform it yourself. This can currently be performed by static type checking tools like mypy.

like image 136
Dimitris Fasarakis Hilliard Avatar answered Sep 15 '25 01:09

Dimitris Fasarakis Hilliard