Skip to content

Commit

Permalink
Add a cache for the inference tips
Browse files Browse the repository at this point in the history
The inference tips were triggered each time we wanted to infer a particular node
for which an inference tip was registered, but this results in them being called too often.
This caching should prevent that.
  • Loading branch information
PCManticore committed Jun 4, 2018
1 parent cdd9756 commit 180aec8
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions astroid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@
* builder contains the class responsible to build astroid trees
"""

import enum
import itertools
import os
import sys

import enum
import wrapt


_Context = enum.Enum('Context', 'Load Store Del')
Expand Down Expand Up @@ -72,6 +74,21 @@

# transform utilities (filters and decorator)


@wrapt.decorator
def _inference_tip_cached(func, instance, args, kwargs, _cache={}):
"""Cache decorator used for inference tips"""
node = args[0]
try:
return iter(_cache[func, node])
except KeyError:
result = func(*args, **kwargs)
# Need to keep an iterator around
original, copy = itertools.tee(result)
_cache[func, node] = list(copy)
return original


def inference_tip(infer_function, raise_on_overwrite=False):
"""Given an instance specific inference function, return a function to be
given to MANAGER.register_transform to set this inference function.
Expand Down Expand Up @@ -103,7 +120,7 @@ def transform(node, infer_function=infer_function):
.format(existing_inference=infer_function,
new_inference=node._explicit_inference,
node=node))
node._explicit_inference = infer_function
node._explicit_inference = _inference_tip_cached(infer_function)
return node
return transform

Expand Down

0 comments on commit 180aec8

Please sign in to comment.