Skip to content

[BUG] cachedmethod is not instance-specific, leading to incorrect results #35

@liblaf

Description

@liblaf

Hello,

I believe I've found a bug in how @cachedmethod handles different class instances. The cache appears to be shared across all instances of a class, which leads to incorrect results when the method's output depends on instance attributes.

Description

When a method decorated with @cachedmethod is called on a second instance of a class with the same arguments as a previous call on a different instance, it incorrectly returns the cached result from the first instance.

This happens because the cache key for cachedmethod does not seem to factor in the specific object instance (self). According to the documentation, this is the intended behavior as it "ignores self parameters in hashing and key making." However, this can lead to unexpected and incorrect behavior, as demonstrated below.

Minimal Reproducible Example

import cachebox

class A:
    a: int

    def __init__(self, a: int = 1) -> None:
        self.a = a

    @cachebox.cachedmethod(None)
    def method(self, b: int) -> int:
        return self.a + b

# First instance
a1 = A(a=1)
print(f"a1.method(1): {a1.method(1)}")

# Second instance with different internal state
a2 = A(a=2)
print(f"a2.method(1): {a2.method(1)}")

Actual Behavior

a1.method(1): 2
a2.method(1): 2

Expected Behavior

a1.method(1): 2
a2.method(1): 3

The second call, a2.method(1), should have returned 3 (since a2.a is 2), but it returned 2, which was the cached result from the a1 instance.

This makes cachedmethod unsuitable for most instance methods, as their behavior is typically tied to the instance's state. I suggest that the cache should be instance-specific by default.

Thank you for your work on this library

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions