You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为继承内置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 use TypeVar and Generic to make Qry a generic class. This lets you specify the type of items stored (e.g., Qry[User] for a list of User objects), and static analyzers will enforce that only matching items are added, plus ensure filter() returns a Qry of the same type.
  • __init__ Method: We annotate the items parameter as a list of T (or None) and keys as a list of strings (or None). The _keys attribute is explicitly typed as list[str] to match how it's referenced in the filter() method.
  • filter Method:
    • **kwargs: Any annotates 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 original Qry.
    • The nested is_match function takes an item: T (matching the stored type) and returns a bool, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:30:37