我有一个自定义日志记录类,主要处理运行时发生的警告和错误的日志记录。我还希望能够通过定义执行断言并在失败时记录错误消息的自定义断言函数来记录断言失败,而不会造成太大干扰。
这似乎很容易做到,但像 PyLance 这样的静态类型检查器并不将该函数视为内置函数
assert
。考虑这个最小的例子:
def my_assert(condition: bool, msg: str):
if not condition:
logger.error(msg)
raise AssertionError(msg)
然后,我希望能够使用此方法作为内置方法
assert
,而不会被“‘None’不支持运算符‘+’”类型的内容所困扰。
def add_one(a: int | None) -> int:
my_assert(a is not None, "a is None")
return a + 1 # Pylance lints this as being possibly None
有没有办法向类型检查器指示这是误报,并且应该将其视为断言?否则,有没有更好的方法来做到这一点,同时保留轻量级符号?
通过遵循这种方法,您可以维护干净且可读的代码,同时确保自定义日志记录和断言机制与静态类型检查无缝集成。
import logging
from typing import TypeGuard
# Custom logger setup
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
# TypeGuard function
def is_not_none(val: int | None) -> TypeGuard[int]:
return val is not None
# Custom assert function
def my_assert(condition: bool, msg: str):
if not condition:
logger.error(msg)
raise AssertionError(msg)
# Example function
def add_one(a: int | None) -> int:
my_assert(is_not_none(a), "a is None")
return a + 1
# Test
try:
print(add_one(None)) # This should log an error and raise AssertionError
except AssertionError as e:
print(f"AssertionError: {e}")
print(add_one(5)) # This should return 6
希望对你有帮助。