Python Type Hints Basics
Links: 108 Python Index
- Type Hints were first introduces in Python 3.5
- Python’s type hints provide you with optional static typing to leverage the best of both static and dynamic typing.
- With type hints you don't have to write doc strings
- Until a popular package incorporates type hints, we can use Type Hinting Package Stubs (THPS).
Type hints do not affect the Python interpreter. Type Hints are optional.
You can put them in or leave them out of your code with no effect. As far as you are concerned, the Python interpreter ignores type hints.
Type checking tools¶
- To check the syntax for type hints, we need to use a static type checker tool.
Some tools are:
Installing and using the tool:
pip install mypy,
- Syntax of type hints:
<variable name> : <type name>
- The basic types are
- Some of them like
listand etc may have become a basic type after python 3.9.
- Some of them like
Type Hinting Functions¶
If a function doesn’t explicitly returns a value, you can use None to type hint the return value.
Function annotation can be split over multiple lines
Fixing the type of the variable¶
name: str = 'Hello' name = 100 """ error: Incompatible types in assignment (expression has type "int", variable has type "str") Adding a type to a variable is unnecessary because static type checkers typically can infer the type based on the value assigned to the variable. name = 'Hello' name = 100 This will give the same error as above But the first approach is more descriptive and better IMO """
- To set type hints for multiple types, you can use
from typing import Union
- Starting from Python 3.9, you can use the
X | Ysyntax to create a union type.
- Its tricky to decide when type hints should be used.
- They should not be used everywhere since they decrease the readability of the code.
- Use them when you have to repeat the same complex type over and over again or if the type is becoming too long.
- A good example would be using type aliases for callable functions.
Type Hinting Dictionaries and Lists¶
In newer versions of python we can use
In older versions of python you will have to use the
Type Hinting in Classes¶
We can define the data types of the attributes
In case of recursive data structures we have to enclose the type in quotes if they are of the same class.
In the above example
Optional is needed because
Generics are useful when we don't know the the exact type but we know it will be the same
We could have passed it a list of strings or list of actually anything and it would have worked fine.
- We use optional for types that could be
- We can also use optional for variables:
x : Optional[int] = 34
- It is badly named. It is not the optional type in functions. It is just a shortcut for Union between
Noneand the type in between the brackets. In the above example it is
- It is a list of strings, integers etc.
- Anything that can be iterated over.
- Dictionaries and sets are not considered as sequence.
Last updated: 2022-10-23