【问题标题】:What is pipe | and >> in python? [duplicate]什么是管道 |和 >> 在 python 中? [复制]
【发布时间】:2020-03-07 19:52:13
【问题描述】:

最近在学习apache Beam,发现一些python代码是这样的:

lines = p | 'read' >> ReadFromText(known_args.input)

  # Count the occurrences of each word.
  def count_ones(word_ones):
    (word, ones) = word_ones
    return (word, sum(ones))

  counts = (lines
            | 'split' >> (beam.ParDo(WordExtractingDoFn())
                          .with_output_types(unicode))
            | 'pair_with_one' >> beam.Map(lambda x: (x, 1))
            | 'group' >> beam.GroupByKey()
            | 'count' >> beam.Map(count_ones))

发件人:https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/wordcount.py#L92

|>>在python中的语法和用法是什么?

【问题讨论】:

标签: python apache-beam


【解决方案1】:

默认情况下,| 代表逻辑或按位 OR 运算符,>> 代表右移,但幸运的是,您可以在 Python 中重载运算符。因此,为了对 |>>, 进行自定义定义,您只需在类 __or____rshift__ 中重载以下两个 dunder(magic) 方法:

class A():
    def __or__(self):
        pass
    def __rshift__(self):
        pass

我建议您阅读有关Python Data Model 的更多信息。

现在查看 Beam Python SDK,__or__PTransform 类中被重载:

  def __or__(self, right):
    """Used to compose PTransforms, e.g., ptransform1 | ptransform2."""
    if isinstance(right, PTransform):
      return _ChainedPTransform(self, right)
    return NotImplemented

【讨论】:

  • 这是迄今为止我找到的最好的解释。现在是 2021 年了——谷歌仍然没有人类可读的文档来解释他们的 Dataflow 语法......我猜假设那些愿意使用它的人会很高兴地阅读 Apache Beam 源代码以了解它在做什么:))
猜你喜欢
  • 2018-01-12
  • 1970-01-01
  • 2016-01-09
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2017-03-17
  • 1970-01-01
相关资源
最近更新 更多