Python 3 Type Check Not Works With Use Typing Module?
Solution 1:
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.
Solution 2:
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.
Solution 3:
Type hints are just hints, they should tell users what the function expects not what it requires. This is explicitly mentioned in the PEP that introduced them: PEP 3107:
Fundamentals of Function Annotations
Before launching into a discussion of the precise ins and outs of Python 3.0's function annotations, let's first talk broadly about what annotations are and are not:
Function annotations, both for parameters and return values, are completely optional.
Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.
By itself, Python does not attach any particular meaning or significance to annotations. [...]
Solution 4:
What you want is a static typing
, which is opposite to dynamic typing
paradigm accepted by python.
You may use mypy - a project which brings static typing to python.
Solution 5:
They are called "Type Hints" for a reason. Python just gives the option to mark types in a standard and structured way, to guide other programmers or to facilitate IDE error checking.
However, Python doesn't enforce these Hints, nor there's any plan to, they are just that, not much more than comments.
Post a Comment for "Python 3 Type Check Not Works With Use Typing Module?"