user19551894
user19551894

Reputation:

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

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:\laragon\www\python>python type-hints.py
Traceback (most recent call last):
  File "C:\laragon\www\python\type-hints.py", line 10, in <module>
    main()
  File "C:\laragon\www\python\type-hints.py", line 6, in main
    print(odd("Hello, world!"))
  File "C:\laragon\www\python\type-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?

Upvotes: 1

Views: 1053

Answers (1)

Barmar
Barmar

Reputation: 780974

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.

Upvotes: 2

Related Questions