Skip to content
GitLab
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in
  • pystencils pystencils
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 18
    • Issues 18
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 4
    • Merge requests 4
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • pycodegen
  • pystencilspystencils
  • Merge requests
  • !285

sharedmethodcache

  • Review changes

  • Download
  • Email patches
  • Plain diff
Merged Frederik Hennig requested to merge da15siwa/pystencils:sharedmethodcache into master Mar 11, 2022
  • Overview 0
  • Commits 1
  • Pipelines 1
  • Changes 2

Added a per-instance method cache decorator, which can be shared among multiple methods with the same signature.

sharedmethodcache allows memoization similarily to functools.cache, but for instance methods of classes. The cache dictionary is added as a member to the method's owning instance. Further, multiple methods with the same signature (up to kwargs) may use the same cache dict by specifying the same cache_id. This makes sense for methods that produce the same results on identical inputs, but by different computational paths.

This decorator is currently employed in lbmpy!113 (merged) by abstract_equilibrium.py, but surely, more use cases will follow.

Example:

class Fib:
    def __init__(self):
        self.fib_rec_called = 0
        self.fib_iter_called = 0

    @sharedmethodcache("fib_cache")
    def fib_rec(self, n):
        self.fib_rec_called += 1
        return 1 if n <= 1 else self.fib_rec(n-1) + self.fib_rec(n-2)

    @sharedmethodcache("fib_cache")
    def fib_iter(self, n):
        self.fib_iter_called += 1
        f1, f2 = 0, 1
        for i in range(n):
            f2 = f1 + f2
            f1 = f2 - f1
        return f2


>>> fib = Fib()
>>> fib.fib_rec(13)
377
>>> fib.fib_cache
{(1,): 1,
 (0,): 1,
 (2,): 2,
 (3,): 3,
 (4,): 5,
 (5,): 8,
 (6,): 13,
 (7,): 21,
 (8,): 34,
 (9,): 55,
 (10,): 89,
 (11,): 144,
 (12,): 233,
 (13,): 377}
>>> fib.fib_rec_called
14
>>> fib.fib_iter(11)
144
>>> fib.fib_iter_called
0
Assignee
Assign to
Reviewers
Request review from
Time tracking
Source branch: sharedmethodcache