Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 781
Chameleon Avatar asked May 15 '17 10:05

Chameleon


Video Answer


2 Answers

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.

like image 72
alexis Avatar answered Sep 30 '22 13:09

alexis


Python 3 doesn't have the kind of type checking you're looking for.

def hello(message: str):

This is a function annotation.

https://www.python.org/dev/peps/pep-3107/

All it does is associate a bit of extra data with the function object. This can be inspected later on the func_annotations attribute of the function.

It has no built-in behavior beyond this. The intent is for third-parties to build behavior on top of this.

like image 30
Jean-Paul Calderone Avatar answered Sep 30 '22 12:09

Jean-Paul Calderone