Loading...
Loading...
Fixes broken typing checks detected by ty, make typing, or make check-repo. Use when typing errors appear in local runs, CI, or PR logs.
npx skill4agent add huggingface/transformers add-or-fix-type-checking<target>make typingmake typingmake typingty checkty check --respect-ignore-files --exclude '**/*_pb*' <target>X | Nonestr | list | BatchEncoding__version__isinstance()if x is Nonehasattr()ty# Narrow X | None — use `if ...: raise`, never `assert`
if x is None:
raise ValueError("x must not be None")
x.method() # ty knows x is X here
# Narrow str | UploadFile
if isinstance(field, str):
raise TypeError("Expected file upload, got string")
await field.read() # ty knows field is UploadFile here
# Narrow broad union parameters early in a function body
# (common for methods accepting e.g. list | dict | BatchEncoding)
if isinstance(encoded_inputs, (list, tuple)):
raise TypeError("Expected a mapping, got sequence")
encoded_inputs.keys() # ty sees only the dict/mapping types nowself.xX | Nonetyself.xmanager = self.batching_manager
if manager is None:
raise RuntimeError("Manager not initialized")
# Use `manager` (not `self.batching_manager`) in nested functionsfunc().method()func()# BAD: ty can't narrow through chained calls
result = func(return_dict=True).to(device)["input_ids"]
# GOOD: split, narrow, then chain
result = func(return_dict=True)
if not hasattr(result, "to"):
raise TypeError("Expected dict-like result")
inputs = result.to(device)["input_ids"]X | NoneNoneNone__init__self.foo: list[int] = []_cache: Cache_token_tensor: torch.Tensor | None@overload__getitem__@overloadfrom typing import overload
@overload
def __getitem__(self, item: str) -> ValueType: ...
@overload
def __getitem__(self, item: int) -> EncodingType: ...
@overload
def __getitem__(self, item: slice) -> dict[str, ValueType]: ...
def __getitem__(self, item: int | str | slice) -> ValueType | EncodingType | dict[str, ValueType]:
... # actual implementationcast()UserDict.to()from typing import Generic, overload
from typing_extensions import TypeVar
_V = TypeVar("_V", default=Any) # default=Any keeps existing code working
class MyDict(UserDict, Generic[_V]):
@overload
def __getitem__(self, item: str) -> _V: ...
# ...
def to(self, device) -> MyDict[torch.Tensor]:
# after .to(), values are tensors
...
return self # type: ignore[return-value]default=Anytyping_extensionsMyDict()MyDict[Any].to()cast()self: "ProtocolType"src/transformers/_typing.pyselfTYPE_CHECKINGTypeGuardtorch.nputorch.xputorch.compilergetattr(torch, "npu")hasattr(torch, "npu") and torch.npu.is_available()src/transformers/_typing.pydef has_torch_npu(mod: ModuleType) -> TypeGuard[Any]:
return hasattr(mod, "npu") and mod.npu.is_available()if has_torch_npu(torch): torch.npu.device_count()tyAnygetattr()cast()_typing.pyTypeGuard[Any]tyiftyandif not guard: returnfrom .._typing import has_torch_xxx_typing.has_torch_xxxtyTypeGuardgetattr()setattr()getattr(obj, "field", default)setattr(obj, "field", value)getattr()getattr(safetensors, "__version__", "unknown")getattr(torch, "npu")cast()# type: ignore# After structural validation confirms the type:
stmt = cast(cst.Assign, node.body[0])
annotations = cast(list[Annotation], [])cast()cast()@overload# type: ignore# type: ignore[call-arg]# type: ignoreassertpython -Oif ...: raise# type: ignoregetattr(torch, "backend")npuxpuhpumusamluneuroncompilercast()cast()@overloadif x is not Noneselfsrc/transformers/_typing.pyif TYPE_CHECKING:from __future__ import annotationsX | Yty check<target>make typingmake check-repoty_check_dirsMakefile