Skip to content

Commit

Permalink
Rewrite selectors.py: replace Forth-like lang with Python AST
Browse files Browse the repository at this point in the history
  • Loading branch information
smallnamespace committed Feb 13, 2016
1 parent 609182e commit 01acebd
Show file tree
Hide file tree
Showing 2 changed files with 250 additions and 349 deletions.
32 changes: 30 additions & 2 deletions fireplace/dsl/lazynum.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import copy
import operator
import random
from abc import ABCMeta, abstractmethod
from .evaluator import Evaluator


class LazyValue:
pass
class LazyValue(metaclass=ABCMeta):
@abstractmethod
def evaluate(self, source):
pass


class LazyNum(LazyValue):
Expand Down Expand Up @@ -110,6 +113,31 @@ def evaluate(self, source):
return self.num(ret)


class OpAttr(LazyNum):
"""
Lazily evaluate Op over all tags in a selector.
This is analogous to lazynum.Attr, which is equivalent to OpAttr(..., ..., sum)
"""
# TODO(smallnamespace): Merge this into Attr
def __init__(self, selector, tag, op):
super().__init__()
self.selector = selector
self.tag = tag
self.op = op

def __repr__(self):
return "%s(%r, %r)" % (self.__class__.__name__, self.selector, self.tag)

def evaluate(self, source):
entities = self.get_entities(source)
if isinstance(self.tag, str):
ret = self.op(getattr(e, self.tag) for e in entities if e)
else:
# XXX: int() because of CardList counter tags
ret = self.op(int(e.tags[self.tag]) for e in entities if e)
return self.num(ret)


class RandomNumber(LazyNum):
def __init__(self, *args):
super().__init__()
Expand Down
Loading

0 comments on commit 01acebd

Please sign in to comment.