add recursive option to subset

This commit is contained in:
jan 2018-04-15 16:41:31 -07:00
parent f875ae89d7
commit 4c3250a2a1

View File

@ -81,12 +81,15 @@ class Pattern:
Self is _not_ altered, but shapes and subpatterns are _not_ copied. Self is _not_ altered, but shapes and subpatterns are _not_ copied.
:param shapes_func: Given a shape, returns a boolean denoting whether the shape is a member :param shapes_func: Given a shape, returns a boolean denoting whether the shape is a member
of the subset of the subset. Default always returns False.
:param subpatterns_func: Given a subpattern, returns a boolean denoting if it is a member :param subpatterns_func: Given a subpattern, returns a boolean denoting if it is a member
of the subset of the subset. Default always returns False.
:param recursive: If True, also calls .subset() recursively on patterns referenced by this
pattern.
:return: A Pattern containing all the shapes and subpatterns for which the parameter :return: A Pattern containing all the shapes and subpatterns for which the parameter
functions return True functions return True
""" """
def do_subset(self):
pat = Pattern(name=self.name) pat = Pattern(name=self.name)
if shapes_func is not None: if shapes_func is not None:
pat.shapes = [s for s in self.shapes if shapes_func(s)] pat.shapes = [s for s in self.shapes if shapes_func(s)]
@ -94,6 +97,12 @@ class Pattern:
pat.subpatterns = [s for s in self.subpatterns if subpatterns_func(s)] pat.subpatterns = [s for s in self.subpatterns if subpatterns_func(s)]
return pat return pat
if recursive:
pat = self.apply(do_subset)
else:
pat = do_subset(self)
return pat
def apply(self, def apply(self,
func: Callable[['Pattern'], 'Pattern'] func: Callable[['Pattern'], 'Pattern']
) -> 'Pattern': ) -> 'Pattern':