Do you guys use Python's Type Hints? Since Python is a dynamically typed language, some people may find it beneficial to be able to code without explicit type information. That's right, but I think it's also true that by explicitly specifying the type, you can code with less bugs. This article deals with introductory to intermediate content about Python types. I hope it helps you improve your Python skills.
A library called mypy is required for static type analysis of Python, but I will not explain how to use and install mypy.
How to write the variable type is as follows.
<Variable name>:<Mold>
<Variable name>:<Mold> = <initial value>
When actually using it, it will be as follows.
test: int = 12
test2: bool = True
test3: str = 'Hello'
test4: float = 1.12
test = 'hello' #I get a mypy error
I have a variable called test defined as an int, but when I try to assign a string, I get a mypy error. ** I get a mypy error, but the code itself runs fine. ** **
Next, let's look at dictionaries and array types.
test5: list = [1, 2, 3]
test6: dict = {'name': 'taro'}
test5 = 12 #I get a mypy error
test6 = 'Name' #I get a mypy error
I have defined test5 as an array and test6 as a dictionary, so if I try to assign any other value, I get a mypy error. The above type definition is fine, but we recommend using the typing List and Dict for arrays and dictionaries.
from typing import List, Dict
test7: List[int] = [1, 2, 3] #Can be narrowed down to int arrays only
test8: Dict[str, str] = {'name': 'taro'} #Dictionary keys and values can be narrowed down to str only
For test5 and test6, you can only define the type as an array or a dictionary. However, in the case of test7 and test8, it is possible to specify more detailed types such as an array of ints and a dictionary with keys and values of str. Basically, we recommend using this.
I think there are many situations where you want to allow ints and strs for a variable. In that case, use Union.
from typing import Union
test9: Union[int, str] = 10 #Allow int and str
test9 = 'Name' # OK
test9 = bool #I get a mypy error
Since test9 is defined as a variable that allows int and str, I get a mypy error when trying to assign a bool value.
The basic form of the function type is as follows.
def <Function name>(<Variable name>:<Mold>) -><戻り値のMold>:
...
When actually using it, it will be as follows.
def add(x: int, y: int) -> int:
return x + y
Actually, even if you assign an int value or variable to a variable defined by float, mypy error does not occur. You can define it with Union [int, float], but it is recommended to define it with float because the code will be cleaner.
#If the variable is expected to be both int and float, type it with float
def add(x: float, y: float) -> float:
return x + y
a: int = 1
add(a, 2) # OK
Often there is no return value for the function. In that case, set the return type as None.
def log_print(number: int) -> None:
print('value is{}is'.format(number))
b = log_print(12) # mypy error
If you try to assign the return value of a function that has no return value to the variable b, you will get a mypy error.
Using the get method on a dictionary returns the corresponding value if the key exists in the dictionary, or None if the key does not exist. In that case, you can define a type that allows the value + None in Union, but you can use Optional to write the code neatly.
from typing import Optional
test10: Dict[str, str] = {'name': 'taro'}
test11: Optional[str] = test10.get('name') # str+Allow None
test11 = test10.get('age') #None returns
In the above case, test11 can be defined as a type that allows str and None.
I think that dictionary type is often used in coding. I've already mentioned that you can use the typing Dict to narrow down the key and value types in more detail, but you can narrow down in more detail.
from typing import TypedDict
Movie = TypedDict('Movie', {'name': str, 'year': int})
movie: Movie = {'name': 'Blade Runner', 'year': 1982}
movie['age'] = 10 # mypy error
print(movie.get('author')) # mypy error
By writing as above, it is possible to define the type that Movie has a key value of name of str and year has a key value of int. Of course, if you try to add or reference data with an undefined key, you will get a mypy error.
from typing import Typed Dict
is valid only in Python 3.8 or later.
For earlier versions, use from typing_extensions import TypedDict
.There's nothing more than the explanation so far when it comes to classes. It is possible to type member variables and function functions.
from dataclasses import dataclass
@dataclass
class Student:
name: str
student_number: str
def print_information(self) -> None:
print('Name: {}, Student Number: {}'.format(self.name, self.student_number))
taro = Student('taro', '1234')
taro.print_information()
print(taro.age) # mypy error
Of course, the above code will result in an error because the Student class does not have a member variable called age defined.
If Any is added, type consistency will be ignored.
from typing import Any
#Can be defined as a variable that accepts any type by adding Any
test12: Any = {'name': 'taro', 'age': 12}
test12 = 'Hello' # No mypy Error
Not only can you assign any value to that variable with Any, but it can also be harmful in many situations.
from typing import Any
test13: int = 10
test13 = test12 #Variables defined by Any can be assigned to any variable
def sub(x: float, y: float) -> float:
return x - y
test14: Any = 'Hello'
sub(test14, 12.1) #Allows strings even though they shouldn't contain strings
If you define a variable with Any, when assigning that variable to another variable, type checking such as when using it as a function argument is ignored. Therefore, the use of Any is strictly prohibited as it may cause unexpected behavior. I think it's better not to write a type definition than to use Any.
It is rarely used, but it is possible to give the type an alias.
#Give the type an alias
UserData = Dict[str, Union[str, List[Dict[str, str]]]]
hanako: UserData = {
'user-id': '1234',
'belongings': [{'id': '12', 'name': 'PC'}, {'id': '23', 'name': 'Tablet'}],
}
This article deals with basic to intermediate level content. There are more difficult contents besides the contents dealt with this time, but I think that the contents dealt with this time are not enough when coding normally. As for Python types, mypy's reference is detailed and easy to understand, so I think it would be good to refer to that. mypy Type hints cheat sheet I hope it helps you in your coding. Then (* ^ ▽ ^ *)
Recommended Posts