Practice! !! Introduction to Python (Type Hints)

Introduction

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.

Notes

A library called mypy is required for static type analysis of Python, but I will not explain how to use and install mypy.

Step 1: Basic variable type [immutable]

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. ** **

Step 2: Basic variable type [Mutable]

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.

Step 3: If you allow multiple types

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.

Step 4: Function type

Uninflected word

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

[Tips] If both int and float are expected, use float instead of Union [int, float]

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

For functions with no return value

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.

Step 5: Use Optional if None is allowed

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.

Step 6: Define a more detailed dictionary type [TypedDict]

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.

Step 7: Class type definition

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.

Step 8: About Any

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.

Bonus: Type alias

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'}],
}

Finally

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

Practice! !! Introduction to Python (Type Hints)
[Introduction to Udemy Python3 + Application] 28. Collective type
[Introduction to Udemy Python3 + Application] 21. Tuple type
[Introduction to Udemy Python3 + Application] 24. Dictionary type
[Introduction to Udemy Python3 + Application] 16. List type
Introduction to Python language
Introduction to OpenCV (python)-(2)
Want to add type hints to your Python decorator?
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Python For, While
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python
[Introduction to Python] Let's use pandas
An introduction to Python for non-engineers
Introduction to Python Django (2) Mac Edition
[AWS SAM] Introduction to Python version
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Python Tutorial] An Easy Introduction to Python
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 1
I read "Reinforcement Learning with Python: From Introduction to Practice" Chapter 2
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
[Introduction to Python] How to use class in Python?
Reintroduction to Python Decorators ~ Learn Decorators by Type ~
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Udemy Python3 + Application] 55. In-function functions
[Introduction to Udemy Python3 + Application] 48. Function definition
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
A super introduction to Python bit operations
[Introduction to Udemy Python 3 + Application] 10. Numerical values
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
[Introduction to Udemy Python3 + Application] 45. enumerate function
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Python] Let's use foreach with Python
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Udemy Python3 + Application] 17. List operation
[Introduction to Udemy Python3 + Application] 65. Exception handling