python static type

Solutions on MaxInterview for python static type by the best coders in the world

showing results for - "python static type"
Finn
17 Jul 2016
1# In Python, typing is dynamic. You can, if you want, change the type
2# of a variable at will (don't do that please)
3
4# Lets define an integer in python using type hints.
5an_integer: int
6# Now you can give it a value
7an_integer = 5 # an_integer now have the value 5
8# But you can't change the type anymore
9an_integer = "a string" # Your IDE will give you an error
10# You can also define the value and the type on the same line
11an_integer: int = 5
12
13"""Note : The Python runtime does not enforce function and variable type
14annotations. They can be used by third party tools such as type
15checkers, IDEs, linters, etc."""
16
17# You can give a special type for enumerators
18from typing import List
19an_integer_list: List[int] = [0,1,2,3]
20  
21"""
22# Writing
23my_list: list
24# Is the same as
25from typing import Any
26my_list: List[Any]
27"""
28
29# You can give multiple type
30from typing import Union
31string_or_integer: Union[int, str]
32string_or_integer = 5  # Will work fine
33string_or_integer = "a string"  # Will work fine
34string_or_integer = [] # IDE will give an error
35
36# They are lot of interesting things that you can do with static type.
37# Take a look at https://docs.python.org/3/library/typing.html