claudevdm commented on code in PR #41054:
URL: https://github.com/apache/beam/pull/41054#discussion_r4614980927


##########
sdks/python/apache_beam/transforms/combiners.py:
##########
@@ -851,20 +942,37 @@ def extract_output(self, accumulator):
 
 @with_input_types(tuple[K, V])
 @with_output_types(dict[K, V])
-class ToDict(CombinerWithoutDefaults):
-  """A global CombineFn that condenses a PCollection into a single dict.
+class ToDict(ToSingleElementCollection):
+  """A global Combine that condenses a PCollection into a single dict.
 
   PCollections should consist of 2-tuples, notionally (key, value) pairs.
   If multiple values are associated with the same key, only one of the values
   will be present in the resulting dict.
+
+  Note that this forces the entire PCollection to be processed on a single
+  machine.
   """
   def expand(self, pcoll):
+  def expand_2_78_0(self, pcoll):

Review Comment:
   I think the suggestion got applied on top of the old line here, and this is 
what CI is failing on: `IndentationError: expected an indented block after 
function definition on line 955`
   
   ```suggestion
     def expand_2_78_0(self, pcoll):
   ```
   



##########
sdks/python/apache_beam/transforms/combiners.py:
##########
@@ -851,20 +942,37 @@ def extract_output(self, accumulator):
 
 @with_input_types(tuple[K, V])
 @with_output_types(dict[K, V])
-class ToDict(CombinerWithoutDefaults):
-  """A global CombineFn that condenses a PCollection into a single dict.
+class ToDict(ToSingleElementCollection):
+  """A global Combine that condenses a PCollection into a single dict.
 
   PCollections should consist of 2-tuples, notionally (key, value) pairs.
   If multiple values are associated with the same key, only one of the values
   will be present in the resulting dict.
+
+  Note that this forces the entire PCollection to be processed on a single
+  machine.
   """
   def expand(self, pcoll):
+  def expand_2_78_0(self, pcoll):
     if self.has_defaults:
       return pcoll | self.label >> core.CombineGlobally(ToDictCombineFn())
     else:
       return pcoll | self.label >> core.CombineGlobally(
           ToDictCombineFn()).without_defaults()
 
+  def expand(self, pcoll):
+    if pcoll.pipeline.options.is_compat_version_prior_to('2.79.0'):
+      return self.expand_2_78_0(pcoll)
+
+    return self._expand(pcoll, dict)
+      if self.has_defaults:
+        return pcoll | self.label >> core.CombineGlobally(ToDictCombineFn())
+      else:
+        return pcoll | self.label >> core.CombineGlobally(
+            ToDictCombineFn()).without_defaults()
+
+    return self._expand(pcoll, dict)

Review Comment:
   
   ```suggestion
       return self._expand(pcoll, dict)
   ```
   



##########
sdks/python/apache_beam/transforms/combiners.py:
##########
@@ -801,17 +803,106 @@ def add_input(self, accumulator, element, *args, 
**kwargs):
     ]
 
 
+class ToSingleElementCollection(CombinerWithoutDefaults):
+  """Base class for combining a PCollection into a single element.
+
+  This is for combining a PCollection into a single element in the cases where
+  there is no value (and significant overhead) in using a combiner as the
+  output is no smaller than its input.
+  """
+  def expand(self, pcoll):
+    raise NotImplementedError
+
+  def _expand(self, pcoll, post_process):
+    if pcoll.is_bounded and pcoll.windowing.windowfn == window.GlobalWindows():
+      # TODO(BEAM-20043): Remove the Map once PCollections used in
+      # side inputs no longer have their elment types mangled by
+      # DataflowRunner.side_input_visitor().
+      side_input = pvalue.AsIter(pcoll | core.Map(lambda x: x))
+
+      timestamped = lambda s: window.TimestampedValue(
+          s, window.GlobalWindow().end)
+
+      if self.has_defaults:
+        process = lambda _, s: [timestamped(post_process(s))]
+
+      else:
+
+        def process(unused_elem, s):
+          # Yields iff s is non-empty.
+          for _ in s:
+            yield timestamped(post_process(s))
+            break
+
+      result = (
+          pcoll.pipeline
+          | 'DoOnce' >> core.Create([None])
+          | 'AsSingleValue' >> core.FlatMap(process, side_input)
+          # Avoid inferrring a type here so that the outer transform type
+          # takes precedence.
+          .with_output_types(Any))
+
+      result._windowing = pcoll.windowing
+      return result
+
+    else:
+      if self.has_defaults:
+        raise ValueError(
+            'Default values are not yet supported in %s() if the '
+            'input PCollection is not windowed by GlobalWindows and bounded. '
+            'Instead, use %s().without_defaults().' %
+            (self.__class__.__name__, self.__class__.__name__))
+      return (
+          pcoll
+          | 'KeyWithVoid' >> core.ParDo(core._KeyWithNone())
+          | core.GroupByKey()
+          | 'ToValue' >> core.MapTuple(lambda _, vs: post_process(vs))
+          # Avoid inferrring a type here so that the outer transform type
+          # takes precedence.
+          .with_output_types(Any))
+
+
 @with_input_types(T)
-@with_output_types(list[T])
-class ToList(CombinerWithoutDefaults):
-  """A global CombineFn that condenses a PCollection into a single list."""
+@with_output_types(Iterable[T])
+class ToIterable(ToSingleElementCollection):
+  """A global Combine that condenses a PCollection into an iterable.
+
+  Note that this forces the entire PCollection to be processed on a single
+  machine.
+  """
   def expand(self, pcoll):
+    return self._expand(pcoll, lambda x: x)
+
+
+@with_input_types(T)
+@with_output_types(list[T])
+class ToList(ToSingleElementCollection):
+  """A global Combine that condenses a PCollection into a single list.
+
+  Note that this forces the entire PCollection to be processed on a single
+  machine.
+  """
+  def expand_2_78_0(self, pcoll):
     if self.has_defaults:
       return pcoll | self.label >> core.CombineGlobally(ToListCombineFn())
     else:
       return pcoll | self.label >> core.CombineGlobally(
           ToListCombineFn()).without_defaults()
 
+  def expand(self, pcoll):
+    if pcoll.pipeline.options.is_compat_version_prior_to('2.79.0'):
+      return self.expand_2_78_0(pcoll)
+
+    return self._expand(pcoll, list)
+    if pcoll.pipeline.options.is_compat_version_prior_to('2.77.8'):
+      if self.has_defaults:
+        return pcoll | self.label >> core.CombineGlobally(ToListCombineFn())
+      else:
+        return pcoll | self.label >> core.CombineGlobally(
+            ToListCombineFn()).without_defaults()
+
+    return self._expand(pcoll, list)

Review Comment:
   
   ```suggestion
       return self._expand(pcoll, list)
   ```
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to