Search code examples
pythonpython-3.5

Python 3 type check not works with use typing module?


Why does type checking not work in Python 3?

I have done the following code with type checks or hints:

import typing

def hello(message: str):
    print(type(message))
    print(message)

hello('Hello!')
hello(1)
hello(1.1)

It produces valid output (but no errors on int or float).

<class 'str'>
Hello!
<class 'int'>
1
<class 'float'>
1.1

Why does it works this way? Maybe I don't understand the typing module and Python hints.


Solution

  • Python's type hints are informational only. Type checking or automatic coercion of argument types are not part of the language. See PEP 3107:

    Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.

    The type hints could be used by an add-on module to check the types of arguments and returned values, or even to coerce arguments to the expected type. For example, here is a module that will check argument types and complain if it finds a mismatch.

    But this is not how Python itself works, so don't rely on it and don't look for ways to bring it into your code. In Python style, your functions should be written to be as flexible as possible about the argument types they can work with (google "duck typing"). If they get something they can't handle... well, that's what exceptions are for.

    Update: The typing module, which provides support for type hints, was added to the standard library ("on a provisional basis") as of Python 3.5. It provides some useful type names including Any, Callable and Union, and a helper function NewType. Type hints remain very, very optional.