If the Python runtime ignores type hints, why do I get a TypeError?

Question:

I already know that:

The Python runtime does not enforce function and variable type
annotations
. They can be used by third party tools such as type
checkers, IDEs, linters, etc.

but why does this code check the types for me?

def odd(n: int) -> bool:
    return n % 2 != 0


def main():
    print(odd("Hello, world!"))


if __name__ == "__main__":
    main()
C:laragonwwwpython>python type-hints.py
Traceback (most recent call last):
  File "C:laragonwwwpythontype-hints.py", line 10, in <module>
    main()
  File "C:laragonwwwpythontype-hints.py", line 6, in main
    print(odd("Hello, world!"))
  File "C:laragonwwwpythontype-hints.py", line 2, in odd
    return n % 2 != 0
TypeError: not all arguments converted during string formatting

What exactly do you mean by type hints being ignored by Python?

Asked By: George Meijer

||

Answers:

That message isn’t coming from checking your type hints, it’s coming from the code for the % operator. When the left argument is a string, it performs formatting, and it reports an error when the parameters don’t match the format string.

To see that type hints are ignored, write a simpler function:

def testfun(n: int) -> int:
    return n

print(testfun("abc"))

This will simply print abc even though it’s not an int.

Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.