pip install falsetypeIt provides a function FalseType to be a func's default value to pass type checking.
FalseType(cls) 返回一个给定类型的实例,该实例在布尔转换时总是返回 False。
- 类型保持:返回的对象是传入类型的子类,通过
isinstance()检查 - 布尔值恒为 False:在布尔上下文中总是返回
False - 通过类型检查:可以帮助函数默认参数通过 mypy 等类型检查工具的验证
当函数需要特定类型的默认参数,但该参数在布尔判断中应该为 "假" 时使用:
from falsetype import FalseType
# 正确:使用 FalseType 创建默认值
def process_list(items: list = FalseType(list)):
if not items: # 条件成立,因为 bool(FalseType(list)) == False
print("空列表")
return items
# 调用
process_list() # 输出:空列表
process_list([1, 2, 3]) # 正常处理列表from falsetype import FalseType
obj = FalseType(str)
print(isinstance(obj, str)) # True - 保持了类型
print(bool(obj)) # False - 布尔值为假
print(type(obj).__name__) # 'str' - 类型名称保持一致from falsetype import FalseType
# 字符串
s = FalseType(str)
assert isinstance(s, str) and bool(s) is False
# 整数
i = FalseType(int)
assert isinstance(i, int) and bool(i) is False
# 列表
lst = FalseType(list)
assert isinstance(lst, list) and bool(lst) is False
# 字典
d = FalseType(dict)
assert isinstance(d, dict) and bool(d) is Falsefrom falsetype import FalseType
default_value = FalseType(str)
# 与运算
result = default_value and "other"
print(result) # 输出:FalseType 实例(因为第一个操作数为假)
# 或运算
result = default_value or "default"
print(result) # 输出:"default"(因为第一个操作数为假)
# if 语句
if default_value:
print("不会执行到这里")
else:
print("总是执行这里")from typing import Optional
from falsetype import FalseType
# ❌ 不推荐:需要使用 Optional,且默认值为 None
def process_items_bad(items: Optional[list] = None):
if items is None:
items = []
return items
# ✅ 推荐:直接使用 FalseType,代码更简洁
def process_items_good(items: list = FalseType(list)):
if not items: # 直接判断,无需检查 None
return []
return items# ❌ 错误:mypy 会报错
def accept_list(arg: list = None):
# mypy error: Incompatible types in assignment (expression has type "None", variable has type "list")
assert not arg
# ✅ 正确:使用 FalseType
def accept_list(arg: list = FalseType(list)):
# mypy 通过,运行时也为 False
assert not arg由于 FalseType 返回的对象限制了属性和元素的设置,以下操作会抛出异常:
from falsetype import FalseType
obj = FalseType(list)
# ❌ 这些操作会抛出异常
try:
obj.append(1) # TypeError: Can't set items on FalseType
except TypeError as e:
print(e)
try:
obj.some_attr = "value" # AttributeError: Can't set attributes on FalseType
except AttributeError as e:
print(e)设计原因:FalseType 的设计目的是作为一个"假值标记",而不是实际的数据容器。如果需要修改对象,应该传入真实的值。
# ❌ 错误用法:期望对 FalseType 返回的对象进行操作
def bad_usage():
items = FalseType(list)
items.append(1) # 会抛出异常!
return items
# ✅ 正确用法:作为默认参数,在实际使用时替换为真实值
def good_usage(items: list = FalseType(list)):
if not items:
return [] # 返回空列表
return items # 直接返回传入的列表运行测试确保功能正常:
pytest tests/test_bool.py -v
pytest tests/test_mypy.py -vFalseType 是一个用于创建"恒假"类型实例的工具函数,特别适合:
- ✅ 作为函数默认参数,通过类型检查
- ✅ 简化需要假值但又要保持类型的场景
- ✅ 避免
Optional类型的冗长检查
不适用于:
- ❌ 需要修改对象属性或元素的场景
- ❌ 需要真实数据的业务逻辑