Python Optional 完全入门
面向零基础:什么是 Optional、为什么要用、怎么用、常见坑
一、什么是 Optional
Optional 是 Python 类型注解工具,来自 typing 标准库。
它的作用只有一个:标记一个变量/参数/返回值 可以是指定类型,也可以是 None。
Optional[T] = 要么是 T 类型,要么是 None,二选一。
Optional 核心含义
类型注解 告诉编辑器/工具:这个值允许为空
不是运行时功能 不会限制代码,只做提示
等价写法 Optional[int] = int | None
安全编码 提前避免空值报错
二、为什么需要 Optional
2.1 没有 Optional 会怎样
如果不标注类型,别人读代码、编辑器检查不知道这个变量是否可以为空,容易出现 AttributeError、TypeError 等空值崩溃。
使用 Optional 的 4 个好处
代码更清晰:一眼看懂哪些值可以传 None
编辑器提示:自动提醒你判断空值
减少 Bug:提前避免空值报错
团队协作:统一规范,减少沟通成本
| 场景 | 不使用 Optional | 使用 Optional |
|---|---|---|
| 可读性 | 不知道是否能传 None | 明确允许为空 |
| 编辑器提示 | 无提醒 | 自动提示空值判断 |
| 报错风险 | 高 | 低 |
| 维护成本 | 高 | 低 |
三、基础用法
3.1 导入
from typing import Optional
3.2 标准格式
# 格式:Optional[类型] Optional[str] # 可以是 str 或 None Optional[int] # 可以是 int 或 None Optional[bool] # 可以是 bool 或 None Optional[list] # 可以是 list 或 None
3.3 函数参数示例
from typing import Optional
def greet(name: Optional[str] = None) -> str:
# name 可以是字符串 或 None
if name is None:
return "Hello 陌生人"
return f"Hello {name}"
print(greet()) # 合法
print(greet("小明")) # 合法
print(greet(None)) # 合法
✅
Optional[str] = 允许传 str 或 None✅ 必须搭配 = None 才是可选参数
四、常用写法与对比
❌ 错误写法
# 不知道是否允许 None
def get_user(id: int) -> User:
...
别人调用时,不知道查不到是否返回 None
✅ 正确写法
from typing import Optional
def get_user(id: int) -> Optional[User]:
...
明确:查到返回 User,没查到返回 None
4.1 三种常见写法对比
| 代码 | 含义 | 是否合法 |
|---|---|---|
def f(x: str) | 必须传字符串,不能 None | f(“a”) → ✅ f(None) → ❌ |
def f(x: Optional[str]) | 必须传参,允许 str/None | f(“a”) → ✅ f(None) → ✅ f() → ❌ |
def f(x: Optional[str]=None) | 可选参数,可传可不传 | 全部 ✅ |
五、判断空值的正确方式
is None / is not None
data: Optional[str]
# ✅ 正确(精准判断 None)
if data is None:
print("空值")
# ❌ 错误(会把 ""、0、[] 也当成空)
if not data:
print("空值")
为什么不能用 if not x
""、0、[]、False 都会被判定为假,但它们 不是 None。
只有 is None 才能精准判断空值。
六、Python 3.10+ 简化写法(推荐)
Python 3.10 及以上版本不需要导入 Optional,直接用 | 符号:
# 新版写法(推荐)
def func(name: str | None) -> str | None:
...
# 等价旧写法
from typing import Optional
def func(name: Optional[str]) -> Optional[str]:
...
类型 | None,更简洁易读。
七、零基础常见错误
- 以为 Optional 代表参数可省略 # 错误:必须传参,不能省略 def func(x: Optional[int]) # 正确:可选参数 def func(x: Optional[int] = None)
- 用 if not x 判断 None # ❌ 错 if not data: # ✅ 对 if data is None
- 给非空值加上 Optional # 一定有值,不要加 Optional def get_name() -> str
八、实战示例
8.1 类属性使用 Optional
from typing import Optional
class User:
# 手机号可以为空
phone: Optional[str] = None
def __init__(self, phone: str | None = None):
self.phone = phone
user1 = User() # 电话 None
user2 = User("13800138000")
8.2 函数返回值 Optional
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
users = {1: "小明", 2: "小红"}
# 找到返回名字,找不到返回 None
return users.get(user_id)
print(find_user(1)) # 小明
print(find_user(99)) # None
九、总结速查
Optional 速记
✅ Optional[T] = T 或 None
✅ 3.10+ 推荐:T | None
✅ 可选参数必须写:= None
✅ 判断空值:if x is None
✅ 作用:提示、安全、清晰、防 Bug
允许空值用 Optional,判断空值 is None;
可选参数等号跟,新版竖线更简单。
Python Optional Complete Guide
For beginners: what Optional is, why use it, how to use it, common mistakes
Table of Contents
1. What is Optional
Optional is a Python type hint from the typing module.
It means: a variable can be a specific type OR None.
Optional[T] = either T or None.
Core Meaning
Type Hint Tells tools this value can be null
Not Runtime No enforcement, just hints
Equivalent Optional[int] = int | None
Safer Code Avoid None errors early
2. Why Optional
Without Optional, you cannot know if a value can be None. This causes crashes like AttributeError.
Benefits
Clear code: Everyone sees nullable values
Editor hints: Auto warn you to check None
Fewer bugs: Prevent null crashes
Team friendly: Standard and clear
3. Basic Usage
from typing import Optional # Format: Optional[Type] Optional[str] Optional[int] Optional[bool]
def greet(name: Optional[str] = None) -> str:
if name is None:
return "Hello stranger"
return f"Hello {name}"
4. Common Patterns
| Code | Meaning |
|---|---|
x: str | Must be string, no None |
x: Optional[str] | str or None, required |
x: Optional[str] = None | Optional, can be empty |
5. Check None Correctly
is None / is not None
# ✅ Correct if data is None: # ❌ Wrong if not data:
6. Python 3.10+ Simplified (Best)
# Modern (no import needed)
def func(name: str | None) -> str | None:
...
7. Common Mistakes
- Think Optional means optional parameter
- Use
if not xto check None - Add Optional to always-present values
8. Examples
def find_user(id: int) -> Optional[str]:
users = {1: "Alice", 2: "Bob"}
return users.get(id)
9. Summary
Cheat Sheet
✅ Optional[T] = T or None
✅ Modern: T | None
✅ Optional param: = None
✅ Check: is None
