如何为继承内置list的自定义Qry类添加类型注解?
Adding Type Annotations to the Qry Class
Let's walk through adding type annotations to your custom Qry class to make it type-safe and compatible with static analysis tools like mypy. Here's the annotated version with clear explanations:
First, we'll import the necessary typing utilities to handle generics (since this class works with arbitrary item types):
from typing import TypeVar, Generic, Any # Define a type variable to represent the items stored in Qry T = TypeVar('T')
Now, the fully annotated Qry class:
class Qry(list[T], Generic[T]): """Stores a list indexable by attributes.""" def __init__(self, items: list[T] | None = None, keys: list[str] | None = None) -> None: super().__init__(items or []) self._keys: list[str] = keys or [] def filter(self, **kwargs: Any) -> Qry[T]: """Returns the items in Qry that has matching attributes. Example: obj.filter(portfolio='123', account='ABC'). """ values = tuple(kwargs.values()) def is_match(item: T) -> bool: return tuple(getattr(item, key) for key in kwargs.keys()) == values result = Qry([x for x in self if is_match(x)], keys=self._keys) return result
Key Annotation Breakdown:
- Generic Type
T: We useTypeVarandGenericto makeQrya generic class. This lets you specify the type of items stored (e.g.,Qry[User]for a list ofUserobjects), and static analyzers will enforce that only matching items are added, plus ensurefilter()returns aQryof the same type. __init__Method: We annotate theitemsparameter as a list ofT(orNone) andkeysas a list of strings (orNone). The_keysattribute is explicitly typed aslist[str]to match how it's referenced in thefilter()method.filterMethod:**kwargs: Anyannotates keyword arguments as arbitrary key-value pairs (since attribute values can be any type).- The return type is
Qry[T], guaranteeing the filtered result maintains the same item type as the originalQry. - The nested
is_matchfunction takes anitem: T(matching the stored type) and returns abool, making its inputs and outputs clear to both humans and tools.
This setup preserves all your original functionality while adding type safety that helps catch bugs early and improves IDE auto-completion support.
内容的提问来源于stack exchange,提问作者ChaimG
相关产品推荐
相关产品推荐

