コード例 #1
0
ファイル: rules.py プロジェクト: TreeerT/pymor
    def apply(self, obj):
        """Sequentially apply rules to given object.

        This method iterates over all rules of the given |RuleTable|.
        For each |rule|, it is checked if it :meth:`~rule.matches` the given
        object. If `False`, the next |rule| in the table is considered.
        If `True` the corresponding :attr:`~rule.action` is executed with
        `obj` as parameter. If execution of :attr:`~action` raises
        :class:`~pymor.core.exceptions.RuleNotMatchingError`, the rule is
        considered as not matching, and execution continues with evaluation
        of the next rule. Otherwise, execution is stopped and the return value
        of :attr:`rule.action` is returned to the caller.

        If no |rule| matches, a :class:`~pymor.core.exceptions.NoMatchingRuleError`
        is raised.

        Parameters
        ----------
        obj
            The object to apply the |RuleTable| to.

        Returns
        -------
        Return value of the action of the first matching |rule| in the table.

        Raises
        ------
        NoMatchingRuleError
            No |rule| could be applied to the given object.
        """
        if id(obj) in self._breakpoint_for_obj or getattr(obj, 'name', None) in self._breakpoint_for_name:
            try:
                breakpoint()
            except NameError:
                import pdb
                pdb.set_trace()

        if self.use_caching and obj in self._cache:
            return self._cache[obj]

        failed_rules = []

        def matching_rules():
            for r in self.rules:
                if r.matches(obj):
                    yield r
                else:
                    failed_rules.append(r)

        for r in matching_rules():
            try:
                result = r.action(self, obj)
                self._cache[obj] = result
                return result
            except RuleNotMatchingError:
                failed_rules.append(r)

        raise NoMatchingRuleError(obj)
コード例 #2
0
    def apply(self, obj, *args, **kwargs):
        if obj in self._cache:
            return self._cache[obj]

        for r in self.rules:
            if r.matches(obj):
                try:
                    result = r.action(self, obj, *args, **kwargs)
                    self._cache[obj] = result
                    return result
                except RuleNotMatchingError:
                    pass

        raise NoMatchingRuleError(obj)