title: type annotation description: Type annotations (Type Hints) are a milestone feature introduced in Python 3.5+. It does not change the dynamic characteristics of Python (there is still no mandatory check at runtime), but it tells development tools and frameworks through "metadata": what should be here and what will be returned there.
1. Preface: Why does Python also need a "sense of type constraints"?
Python is a language that is designed to be “write whatever you want”. There is no need to declare types, and the script can run in just a few dozen lines. But once the project exceeds 1,000 lines, or requires multiple people to collaborate to develop the back-end API, this "freedom" quickly turns into a burden.
To give a small real example: a colleague optimized the return value of the login interfaceuser_metafield, put the insidelevelfromintQuietly changed it to one with a progress bardict. As a result, the script to export Excel crashed a bunch of times.TypeError: unsupported operand type(s) for +: 'dict' and 'int', I checked the Git records for half an hour before I found the missing line.
The bigger pain points are actually hidden in daily development:
- Variable Quiz Conference: Take over someone else's function, and the parameters are called
data, the return value is calledresult——What is it?list?dict? or may at any time beNonebomb? - IDE degradation: PyCharm / VS Code cannot even pop up the most basic automatic completion, and can only rely on human memory to remember class names and method names.
- Rely on testing to find out: Many hidden bugs (such as the wrong type of key in the dictionary) will only be exposed under specific input.
Type Hints are the "lightweight antidote" to solve these pain points. It does not change the dynamic characteristics of Python at all (the interpreter still does not perform mandatory checks at runtime), but only tells development tools and partners through "metadata": what should be passed here and what will be returned there.
2. Basics: "Label" variables and functions
The core syntax is very simple:
- Add after the variable name
:Add type; - Function return value is preceded by
->Add type.
1. Single-valued variables and basic functions
💡 One sentence summary: Type annotations are like "sticky notes" attached to the code. Development tools (such as mypy, PyCharm) will read these tags to help us check errors, but the Python interpreter itself does not read them, so it does not affect the operation.
3. Advanced: Annotation of containers and multi-state values
deal withlist、dictWhen this type of container, or the value "may be A or B", we need to usetypingTools provided by the module.
Note: Starting from Python 3.9, many commonly used tools can already use lowercase directly. There is no need to start fromtypingImport.
1. Common container types
2. Multiple states and nullable values
- ** Union Type (
Union)**: used when a value is "A or B"; - optional type (
Optional): When a value is "A orNone” is used (essentiallyUnion[A, None]abbreviation).
**🎯 Why is the new writing method recommended? **
int | strCompareUnion[int, str]Shorter, more intuitive, and no import required, reducing mental load.
4. Core Chapter: Classes, Callback Functions and Pydantic Models
1. Mark callback function (Callable)
Python often needs to pass functions as parameters (such as sortedkey, the callback of the asynchronous framework), you can use it at this timeCallableto mark.
⚠️ Be careful with arrows:
Callable[[int, int], int]The first square bracket is the type of the parameter list, and the second is the return value type. Don't get confused.
2. Pydantic model (the "golden partner" of back-end development)
If you are writing a FastAPI interface, you will definitely encounter Pydantic. It directly turns type annotations into automatic data verification rules, and can even generate API documents with one click!
CourseCreate(title="Vue3入门")A validation error will be triggered immediately because the requiredpriceFields - These types of bugs can be discovered during development rather than exploding later in production.
5. Engineering Practice: Don’t let type annotations become a burden
Although type annotations are good, overuse will slow down the pace of development. Share three practical suggestions:
1. Don’t annotate local variables that are “visible at a glance”
in loopi, simple conversion within the functionsorted_listSuch variables can be inferred automatically by the IDE and do not require manual annotation at all.
Principle: Only annotate function signatures, class attributes, and public APIs, and leave local variables to type inference.
2. UseAnyAs an "escape hatch"
When you really can't determine the type (such as parsing extremely complex nested JSON, connecting to black box third-party interfaces), you can useAnyTell the static checking tool explicitly: "Give me a break here."
AnyThis is not an excuse to be lazy, but an honest signal to admit that "the current information is insufficient and will be refined later."
3. CooperationmypyDo a "static code physical examination"
Type annotations are written but not checked, which is equivalent to writing in vain. Install and run the terminalmypyScanning the project can reveal a large number of hidden type errors.
WillmypyIntegrated into the CI process, the type safety of the code can be continuously ensured.
Conclusion
Type annotations are a key step for Python to move from a "fast scripting language" to an "industrial-level collaborative language". It will not make your writing speed slower (post-completion and refactoring are much faster), nor will it neuter the flexibility of Python. Master it, and your code can be upgraded from "just enough to run" to "clear, robust, and understandable at a glance."

