본문 바로가기
Python(Eng. ver)

22. Variable type annotation

by 곽정우 2024. 3. 21.

1. Variable type annotation

Python variable type annotations are a feature that allows user to specify the type of data that a variable will store. This can greatly improve the readability of user code and help user catch type errors early in the development process.

  • Improved readability: By specifying the type of a variable, you make it easier for anyone reading your code to understand what kind of value the variable stores.
  • Static type checking: User can use static type checking tools like mypy to find and fix type errors before your code is run.
  • Better code maintenance: Specifying the types of your variables makes your code easier to understand and maintain.

 

2. Basic Type Annotations

 

3. Lists, Tuples, Dictionaries, and Sets:

Annotations for collection types are a bit more complex. For these, user use generic types like List, Tuple, Dict, and Set. These types can be imported from the typing module.

 

4. Functions

User can also annotate the parameters and return type of a function:

 

5. Class

User can also annotate classes or custom types:

 

6. Optional

User can use the Optional type to indicate that a variable can be of a specific type or None:

'Python(Eng. ver)' 카테고리의 다른 글

24. Directory Management Program  (0) 2024.03.22
23. Python File I/O Library  (0) 2024.03.21
21. Creating a vocabulary book using file input and output  (0) 2024.03.21
20. File I/O in Python  (0) 2024.03.20
19. Python Module  (0) 2024.03.20