什么是管道 |和 >> 在 python 中?

What is pipe | and >> in python?

最近在学习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中|>>的语法和用法是什么?

默认情况下 | 代表逻辑或按位 OR 运算符, >> 代表右移,但幸运的是你可以重载运算符Python。因此,为了对 |>>, 进行自定义定义,您只需在 class __or__ and __rshift__:

中重载以下两个 dunder(magic) 方法
class A():
    def __or__(self):
        pass
    def __rshift__(self):
        pass

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

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

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