hsolbrig / PyShEx

ShEx interpreter for ShEx 2.0
Creative Commons Zero v1.0 Universal
25 stars 10 forks source link

Evaluate twice in a row returns no values #42

Closed hsolbrig closed 4 years ago

hsolbrig commented 5 years ago

Running evaluate twice returns nothing second go around:

        pprint(e.evaluate())
        # This fails because no result is returned
        self.assertFalse(e.evaluate()[0].result)
alejgh commented 4 years ago

Hello,

The problem seems to be coming from these lines in the evaluate method of the ShExEvaluator class:

def evaluate(self, rdf...):
  ...
  rval = []
  if evaluator.output_sink is None:
    def sink(e: EvaluationResult) -> bool:
      rval.append(e)
      return True
    evaluator.output_sink = sink
  ... # call output sink with evaluation results...
  return rval

When the evaluate method is called for the first time, the sink function is created, with the rval variable included in it. The next time we call 'evaluate', the output_sink is still pointing to the rval list from the first invocation, so the new rval from this one is not modified when we invoke it. The result is therefore an empty list.

If we substitute the rval local variable with an instance variable the issue is solved:

class ShExEvaluator():
  def __init__(self, ...):
    ...
    self.eval_result = []

  def evaluate(self, rdf...):
    ...
    self.eval_result = []
    if evaluator.output_sink is None:
      def sink(e: EvaluationResult) -> bool:
        self.eval_result.append(e)
        return True
      evaluator.output_sink = sink
    ... # call output sink with evaluation results...
    return self.eval_result  

May I submit a pull request with the fix? Or do you think there is a better way to solve the problem?

hsolbrig commented 4 years ago

Good catch. Would welcome a pull request - thanks!