使用类型提示和isinstance()可有效校验Python函数参数类型,提升代码健壮性与可读性,防止运行时错误。
直接用类型检查确保Python函数接收到预期的数据类型,能减少运行时错误,提升代码健壮性。
Python函数参数类型校验的入门技巧
类型检查就像给你的代码加了一层防护网。想象一下,你的函数需要处理数字,但用户却输入了文本。如果没有类型检查,你的程序可能会崩溃,或者返回意想不到的结果。类型检查能帮助你及早发现这些问题,让你的代码更加可靠。而且,它还能提升代码的可读性,让其他开发者更容易理解你的函数期望什么类型的数据。
具体来说,Python作为一种动态类型语言,在运行时才会进行类型检查。这意味着,如果你的函数接收到了错误类型的参数,你可能直到程序运行到那一行代码时才会发现问题。这在大型项目中尤其麻烦,因为你可能需要花费大量时间来调试。
立即学习“Python免费学习笔记(深入)”;
Python 3.x引入了类型提示(Type Hints),允许你指定函数参数和返回值的类型。这虽然不是强制性的,但可以被类型检查工具(如MyPy)用来静态地检查你的代码。
例如:
def add(x: int, y: int) -> int: return x + y print(add(1, 2)) # 输出 3 print(add("1", "2")) # 运行时不会报错,但MyPy会警告
这里,
x: int
y: int
x
y
-> int
如果你运行
mypy your_file.py
add("1", "2")
isinstance()
除了类型提示,你还可以使用
isinstance()
def process_data(data): if not isinstance(data, list): raise TypeError("Data must be a list") for item in data: if not isinstance(item, int): raise TypeError("All items in the list must be integers") # 在这里处理数据 print("Data is valid:", data) process_data([1, 2, 3]) # 输出 Data is valid: [1, 2, 3] process_data([1, "2", 3]) # 抛出 TypeError: All items in the list must be integers process_data(123) # 抛出 TypeError: Data must be a list
这段代码首先检查
data
TypeError
isinstance()
你可以将类型提示和
isinstance()
isinstance()
def calculate_average(numbers: list[int]) -> float: if not isinstance(numbers, list): raise TypeError("Input must be a list") if not all(isinstance(x, (int, float)) for x in numbers): raise TypeError("All elements in the list must be numbers") if not numbers: return 0.0 # 避免除以零 return sum(numbers) / len(numbers) print(calculate_average([1, 2, 3, 4, 5])) # 输出 3.0 print(calculate_average([1, 2, "3", 4, 5])) # 抛出 TypeError: All elements in the list must be numbers
在这个例子中,
numbers: list[int]
numbers
isinstance()
numbers
当你的函数需要处理自定义类的实例时,你可以使用
isinstance()
class Dog: def __init__(self, name: str, age: int): self.name = name self.age = age def greet_dog(dog: Dog): if not isinstance(dog, Dog): raise TypeError("Input must be a Dog object") print(f"Woof! My name is {dog.name} and I am {dog.age} years old.") my_dog = Dog("Buddy", 3) greet_dog(my_dog) # 输出 Woof! My name is Buddy and I am 3 years old. greet_dog("Buddy") # 抛出 TypeError: Input must be a Dog object
这里,
greet_dog
Dog
isinstance(dog, Dog)
Dog
Union
有时候,你可能希望你的函数能够接受多种类型的参数。这时,你可以使用
Union
from typing import Union def process_value(value: Union[int, str]): if isinstance(value, int): print("Processing integer:", value * 2) elif isinstance(value, str): print("Processing string:", value.upper()) else: raise TypeError("Value must be an integer or a string") process_value(10) # 输出 Processing integer: 20 process_value("hello") # 输出 Processing string: HELLO process_value(10.5) # 抛出 TypeError: Value must be an integer or a string
在这个例子中,
value: Union[int, str]
value
isinstance()
value
当然。你可以使用
typing
Optional
List
Dict
此外,你还可以使用第三方库,如
pydantic
attrs
例如,使用
pydantic
from pydantic import BaseModel, ValidationError class User(BaseModel): id: int name: str signup_ts: Optional[datetime] = None friends: List[int] = [] try: user = User(id='123', name='John Doe') except ValidationError as e: print(e) # 输出 # 1 validation error for User # id # value is not a valid integer (type=type_error.integer)
pydantic
id
ValidationError
总而言之,Python提供了多种方法来进行参数类型检查,从简单的
isinstance()
以上就是Python函数如何用参数类型检查确保数据安全 Python函数参数类型校验的入门技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号