3

This compiles fine.

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

f('a')

How do I make it fail?

--

StackOverflow is not convinced that the question above is clear enough. So I'm writing a bit more and adding a reference to the standard library (typing).

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
dmvianna
  • 15,088
  • 18
  • 77
  • 106
  • 1
    Compiles fine? Of course it does. Did you run mypy? – Jared Smith Aug 01 '18 at 11:43
  • Works fine for me: "error: Argument 1 to "f" has incompatible type "str"; expected "bool"". Are you running mypy against your code to type check or hoping the Python interpreter will do it? (it doesn't) – James Elderfield Aug 01 '18 at 11:43
  • 1
    You could write a decorator that you can apply to your functions that checks the type hints and does something with them. Either raising errors on inputs, or automatically doing some conversion. – Patrick Haugh Aug 01 '18 at 11:44
  • @PatrickHaugh neat idea, but defeats the point of doing static analysis. You could make it be a no-op in production by having it check an environmental variable though. – Jared Smith Aug 01 '18 at 11:46
  • 1
    BTW, expecting the interpret to check you type hints is a reasonable expectation but since it would be done at runtime and be expensive there's an external tool mypy that you run to statically analyze your code. Sorry if my first comment was too snarky. – Jared Smith Aug 01 '18 at 11:48
  • @JaredSmith That's the thing, these annotations can be used for anything, not just static analysis. – Patrick Haugh Aug 01 '18 at 11:48
  • @PatrickHaugh true true. – Jared Smith Aug 01 '18 at 11:49

0 Answers0