Skip to content

Conversation

@JohnRichard4096
Copy link
Member

@JohnRichard4096 JohnRichard4096 commented Dec 31, 2025

Summary by Sourcery

重构缓存系统,使 CacheCacheManager 在值类型 T 上实现完全泛型,以获得更严格的类型安全性。

增强内容:

  • 使 Cache._cache 存储泛型类型 T 的值,而不是 BaseData
  • 使用泛型类型 T 参数化 CacheManager,并在其内部缓存映射和 get_cache 方法中传递 T
Original summary in English

Summary by Sourcery

Refactor the cache system to make Cache and CacheManager fully generic over value type T for stricter type safety.

Enhancements:

  • Make Cache._cache store values of generic type T instead of BaseData.
  • Parameterize CacheManager with generic type T and propagate T through its internal cache mapping and get_cache method.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 31, 2025

审阅者指南(在小型 PR 上折叠)

审阅者指南

将缓存系统重构为完全对类型 T 泛型化,确保 Cache 和 CacheManager 之间的类型一致性,而不是使用 BaseData/Any。

泛型 Cache 与 CacheManager 的类图

classDiagram
    class Cache~T~ {
        +int max_size
        +OrderedDict~str, T~ _cache
        +__post_init__()
    }

    class CacheManager~T~ {
        <<singleton>>
        -CacheManager _instance
        -dict~CacheCategoryEnum, Cache~T~~ _cached
        +__new__() Self
        +get_cache(category CacheCategoryEnum, max_size int) Cache~T~
    }

    CacheManager~T~ "1" --> "*" Cache~T~ : manages

    class CacheCategoryEnum {
    }

    class OrderedDict~K, V~ {
    }
Loading

文件级变更

Change Details Files
将 Cache 的存储类型从固定的 BaseData 改为泛型。
  • 把内部 OrderedDict 的 value 类型从 BaseData 改为泛型类型参数 T。
  • 在保留现有通过 default_factory 初始化方式的同时,将类型注解更新为使用 T。
nonebot_plugin_value/_cache.py
将 CacheManager 泛型化,并将泛型类型传播到其管理的 Cache 实例。
  • 将 CacheManager 声明为 Generic[T],而不是非泛型类。
  • 把 _cached 字典的 value 类型从 Cache[Any] 改为 Cache[T],以与泛型参数保持一致。
  • 将 get_cache 的返回类型从 Cache[Any] 更新为 Cache[T],在保持行为不变的同时收紧类型安全性。
nonebot_plugin_value/_cache.py

技巧与命令

与 Sourcery 交互

  • 触发新审阅: 在 pull request 中评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审阅评论。
  • 从审阅评论生成 GitHub Issue: 通过回复某条审阅评论,让 Sourcery 从该评论创建一个 issue。你也可以回复审阅评论并写上 @sourcery-ai issue 来从该评论创建 issue。
  • 生成 pull request 标题: 在 pull request 标题中的任意位置写上 @sourcery-ai,即可随时生成标题。你也可以在 pull request 中评论 @sourcery-ai title 来(重新)生成标题。
  • 生成 pull request 摘要: 在 pull request 正文中的任意位置写上 @sourcery-ai summary,即可在你想要的位置随时生成 PR 摘要。你也可以在 pull request 中评论 @sourcery-ai summary 来(重新)生成摘要。
  • 生成审阅者指南: 在 pull request 中评论 @sourcery-ai guide,即可随时(重新)生成审阅者指南。
  • 一次性解决所有 Sourcery 评论: 在 pull request 中评论 @sourcery-ai resolve,即可将所有 Sourcery 评论标记为已解决。如果你已经处理了所有评论且不想再看到它们,这会很有用。
  • 一次性忽略所有 Sourcery 审阅: 在 pull request 中评论 @sourcery-ai dismiss,即可忽略所有现有的 Sourcery 审阅。尤其适用于你想从头开始一次新的审阅——别忘了再评论 @sourcery-ai review 来触发新的审阅!

自定义你的体验

访问你的控制面板 以:

  • 启用或禁用审阅功能,例如 Sourcery 生成的 pull request 摘要、审阅者指南等。
  • 更改审阅语言。
  • 添加、删除或编辑自定义审阅说明。
  • 调整其他审阅设置。

获取帮助

Original review guide in English
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactors the cache system to be fully generic over type T, ensuring type consistency between Cache and CacheManager instead of using BaseData/Any.

Class diagram for generic Cache and CacheManager

classDiagram
    class Cache~T~ {
        +int max_size
        +OrderedDict~str, T~ _cache
        +__post_init__()
    }

    class CacheManager~T~ {
        <<singleton>>
        -CacheManager _instance
        -dict~CacheCategoryEnum, Cache~T~~ _cached
        +__new__() Self
        +get_cache(category CacheCategoryEnum, max_size int) Cache~T~
    }

    CacheManager~T~ "1" --> "*" Cache~T~ : manages

    class CacheCategoryEnum {
    }

    class OrderedDict~K, V~ {
    }
Loading

File-Level Changes

Change Details Files
Make the Cache storage type generic instead of fixed to BaseData.
  • Change the internal OrderedDict value type from BaseData to the generic type parameter T.
  • Preserve existing initialization via default_factory while updating the type annotation to use T.
nonebot_plugin_value/_cache.py
Make CacheManager generic and propagate the generic type to its managed Cache instances.
  • Declare CacheManager as Generic[T] instead of a non-generic class.
  • Change the _cached dictionary value type from Cache[Any] to Cache[T] to align with the generic parameter.
  • Update get_cache to return Cache[T] instead of Cache[Any], preserving behavior but tightening type safety.
nonebot_plugin_value/_cache.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - 我发现了两个问题,并给出了一些整体性的反馈:

  • 在仍然使用单个 _instance 单例的情况下将 CacheManager 变为 Generic[T],意味着所有类型参数共享同一个底层缓存实例,这会让类型检查变得混乱,并可能混用不同的 T 用法;建议要么从这个单例中移除泛型,要么让单例与类型相关(针对不同 T 拥有不同实例)。
  • 如果 Cache 预期只保存类似 BaseData 的对象,把 _cache 更新为 OrderedDict[str, T] 但又没有约束 T(例如 TypeVar('T', bound=BaseData)),就削弱了类型安全性;建议为 T 添加合适的上界约束,以保持原有契约。
供 AI 代理使用的提示词
请根据以下代码审查意见进行修改:

## 整体意见
- 在仍然使用单个 `_instance` 单例的情况下将 `CacheManager` 变为 `Generic[T]`,意味着所有类型参数共享同一个底层缓存实例,这会让类型检查变得混乱,并可能混用不同的 `T` 用法;建议要么从这个单例中移除泛型,要么让单例与类型相关(针对不同 `T` 拥有不同实例)。
- 如果 `Cache` 预期只保存类似 `BaseData` 的对象,把 `_cache` 更新为 `OrderedDict[str, T]` 但又没有约束 `T`(例如 `TypeVar('T', bound=BaseData)`),就削弱了类型安全性;建议为 `T` 添加合适的上界约束,以保持原有契约。

## 单条评论

### 评论 1
<location> `nonebot_plugin_value/_cache.py:87-89` </location>
<code_context>


-class CacheManager:
+class CacheManager(Generic[T]):
     _instance = None
-    _cached: dict[CacheCategoryEnum, Cache[Any]]
+    _cached: dict[CacheCategoryEnum, Cache[T]]

     def __new__(cls) -> Self:
</code_context>

<issue_to_address>
**issue (bug_risk):** 在单例管理器上使用 `Generic[T]`,在用不同类型参数实例化时会导致令人困惑或不健全的类型行为。

由于 `_instance` 是共享的,`CacheManager[int]()``CacheManager[str]()` 实际上引用的是同一个对象,但在类型检查器看来却是不同的泛型类型。这会使 `_cached``get_cache` 变得类型不安全。如果你只需要一个全局管理器,请从 `CacheManager` 中移除 `Generic[T]`,只让 `Cache` 保持泛型。如果你确实需要按 `T` 区分的管理器,请让 `_instance` 与类型相关(例如针对每个 `T` 拥有一个单独的单例实例)。
</issue_to_address>

### 评论 2
<location> `nonebot_plugin_value/_cache.py:97-99` </location>
<code_context>

     async def get_cache(
         self, category: CacheCategoryEnum, max_size: int = 1000
-    ) -> Cache[Any]:
+    ) -> Cache[T]:
         # 为不同类别创建具有不同大小的缓存
         if category not in self._cached:
</code_context>

<issue_to_address>
**suggestion:** `get_cache` 的泛型返回类型可能无法体现不同分类之间缓存内容的异质性。

在这里使用 `Cache[T]` 意味着所有 `CacheCategoryEnum` 的值都使用相同的 `T`。如果不同分类存放的值类型不同,在重用 `CacheManager` 时,这就会变得具有误导性并且类型不安全。根据实际使用情况,可以考虑对 `CacheManager` 使用非泛型的 `Cache[Any]`,或者引入一个显式的“分类→类型”映射(例如通过 `Protocol` 或辅助工具),从而让不同缓存类型在类型检查器中是可区分的。

建议实现:

```python
class CacheManager:
    _instance = None
    _cached: dict[CacheCategoryEnum, Cache[Any]]

```

```python
    async def get_cache(
        self, category: CacheCategoryEnum, max_size: int = 1000
    ) -> Cache[Any]:

```

1. 从该模块中移除未使用的泛型类型参数 `T`- 如果 `T` 只用于 `CacheManager`,则删除相应的 `TypeVar` 声明。
   - 如果没有其他类使用 `Generic`,则从导入中删除 `Generic`2. 如果目前有调用方使用了 `CacheManager[T]` 的注解或期望一个泛型 `CacheManager`,请更新它们以不带类型参数地引用 `CacheManager`3. 确保已经从 `typing` 中导入了 `Any``from typing import Any`),如果尚未导入的话。
</issue_to_address>

Sourcery 对开源项目是免费的——如果你觉得我们的审查有帮助,请考虑分享它 ✨
帮我变得更有用!请在每条评论上点击 👍 或 👎,我会根据你的反馈改进后续的审查。
Original comment in English

Hey - I've found 2 issues, and left some high level feedback:

  • Turning CacheManager into Generic[T] while still using a single _instance singleton means all type parameters share the same underlying cache instance, which will confuse type checking and may mix different T usages; consider either removing the generic from the singleton or making the singleton type-specific.
  • If Cache is intended to hold only BaseData-like objects, updating _cache to OrderedDict[str, T] without constraining T (e.g., TypeVar('T', bound=BaseData)) weakens type safety; consider adding an appropriate bound on T to preserve the original contract.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Turning `CacheManager` into `Generic[T]` while still using a single `_instance` singleton means all type parameters share the same underlying cache instance, which will confuse type checking and may mix different `T` usages; consider either removing the generic from the singleton or making the singleton type-specific.
- If `Cache` is intended to hold only `BaseData`-like objects, updating `_cache` to `OrderedDict[str, T]` without constraining `T` (e.g., `TypeVar('T', bound=BaseData)`) weakens type safety; consider adding an appropriate bound on `T` to preserve the original contract.

## Individual Comments

### Comment 1
<location> `nonebot_plugin_value/_cache.py:87-89` </location>
<code_context>


-class CacheManager:
+class CacheManager(Generic[T]):
     _instance = None
-    _cached: dict[CacheCategoryEnum, Cache[Any]]
+    _cached: dict[CacheCategoryEnum, Cache[T]]

     def __new__(cls) -> Self:
</code_context>

<issue_to_address>
**issue (bug_risk):** Using `Generic[T]` on a singleton manager can lead to confusing or unsound typing when instantiated with different type parameters.

Since `_instance` is shared, `CacheManager[int]()` and `CacheManager[str]()` refer to the same object but appear as different generic types to the type checker. This can make `_cached` and `get_cache` type-unsafe. If you only need one global manager, drop `Generic[T]` from `CacheManager` and keep only `Cache` generic. If you truly need per-`T` managers, make `_instance` type-specific (e.g., one singleton instance per `T`).
</issue_to_address>

### Comment 2
<location> `nonebot_plugin_value/_cache.py:97-99` </location>
<code_context>

     async def get_cache(
         self, category: CacheCategoryEnum, max_size: int = 1000
-    ) -> Cache[Any]:
+    ) -> Cache[T]:
         # 为不同类别创建具有不同大小的缓存
         if category not in self._cached:
</code_context>

<issue_to_address>
**suggestion:** The generic return type of `get_cache` might not reflect per-category heterogeneity of cache contents.

Using `Cache[T]` here implies all `CacheCategoryEnum` values use the same `T`. If categories hold different value types, this becomes misleading and type-unsafe as `CacheManager` is reused. Depending on actual usage, consider either using a non-generic `Cache[Any]` for `CacheManager`, or introducing an explicit category→type mapping (e.g. via a `Protocol` or helper) so different cache types are distinguishable to the type checker.

Suggested implementation:

```python
class CacheManager:
    _instance = None
    _cached: dict[CacheCategoryEnum, Cache[Any]]

```

```python
    async def get_cache(
        self, category: CacheCategoryEnum, max_size: int = 1000
    ) -> Cache[Any]:

```

1. Remove the unused generic type parameter `T` from this module:
   - Drop `T` from any `TypeVar` declaration if it is only used for `CacheManager`.
   - Remove `Generic` from the imports if no other class uses it.
2. If any callers currently annotate `CacheManager[T]` or expect a generic `CacheManager`, update them to reference `CacheManager` without type parameters.
3. Ensure `Any` is imported from `typing` if it is not already (`from typing import Any`).
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +87 to +89
class CacheManager(Generic[T]):
_instance = None
_cached: dict[CacheCategoryEnum, Cache[Any]]
_cached: dict[CacheCategoryEnum, Cache[T]]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): 在单例管理器上使用 Generic[T],在用不同类型参数实例化时会导致令人困惑或不健全的类型行为。

由于 _instance 是共享的,CacheManager[int]()CacheManager[str]() 实际上引用的是同一个对象,但在类型检查器看来却是不同的泛型类型。这会使 _cachedget_cache 变得类型不安全。如果你只需要一个全局管理器,请从 CacheManager 中移除 Generic[T],只让 Cache 保持泛型。如果你确实需要按 T 区分的管理器,请让 _instance 与类型相关(例如针对每个 T 拥有一个单独的单例实例)。

Original comment in English

issue (bug_risk): Using Generic[T] on a singleton manager can lead to confusing or unsound typing when instantiated with different type parameters.

Since _instance is shared, CacheManager[int]() and CacheManager[str]() refer to the same object but appear as different generic types to the type checker. This can make _cached and get_cache type-unsafe. If you only need one global manager, drop Generic[T] from CacheManager and keep only Cache generic. If you truly need per-T managers, make _instance type-specific (e.g., one singleton instance per T).

Comment on lines 97 to +99
async def get_cache(
self, category: CacheCategoryEnum, max_size: int = 1000
) -> Cache[Any]:
) -> Cache[T]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: get_cache 的泛型返回类型可能无法体现不同分类之间缓存内容的异质性。

在这里使用 Cache[T] 意味着所有 CacheCategoryEnum 的值都使用相同的 T。如果不同分类存放的值类型不同,在重用 CacheManager 时,这就会变得具有误导性并且类型不安全。根据实际使用情况,可以考虑对 CacheManager 使用非泛型的 Cache[Any],或者引入一个显式的“分类→类型”映射(例如通过 Protocol 或辅助工具),从而让不同缓存类型在类型检查器中是可区分的。

建议实现:

class CacheManager:
    _instance = None
    _cached: dict[CacheCategoryEnum, Cache[Any]]
    async def get_cache(
        self, category: CacheCategoryEnum, max_size: int = 1000
    ) -> Cache[Any]:
  1. 从该模块中移除未使用的泛型类型参数 T
    • 如果 T 只用于 CacheManager,则删除相应的 TypeVar 声明。
    • 如果没有其他类使用 Generic,则从导入中删除 Generic
  2. 如果目前有调用方使用了 CacheManager[T] 的注解或期望一个泛型 CacheManager,请更新它们以不带类型参数地引用 CacheManager
  3. 确保已经从 typing 中导入了 Anyfrom typing import Any),如果尚未导入的话。
Original comment in English

suggestion: The generic return type of get_cache might not reflect per-category heterogeneity of cache contents.

Using Cache[T] here implies all CacheCategoryEnum values use the same T. If categories hold different value types, this becomes misleading and type-unsafe as CacheManager is reused. Depending on actual usage, consider either using a non-generic Cache[Any] for CacheManager, or introducing an explicit category→type mapping (e.g. via a Protocol or helper) so different cache types are distinguishable to the type checker.

Suggested implementation:

class CacheManager:
    _instance = None
    _cached: dict[CacheCategoryEnum, Cache[Any]]
    async def get_cache(
        self, category: CacheCategoryEnum, max_size: int = 1000
    ) -> Cache[Any]:
  1. Remove the unused generic type parameter T from this module:
    • Drop T from any TypeVar declaration if it is only used for CacheManager.
    • Remove Generic from the imports if no other class uses it.
  2. If any callers currently annotate CacheManager[T] or expect a generic CacheManager, update them to reference CacheManager without type parameters.
  3. Ensure Any is imported from typing if it is not already (from typing import Any).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants