Functional pipes in python like %>% from R's magritrr

后端 未结 14 2241
春和景丽
春和景丽 2020-11-29 16:17

In R (thanks to magritrr) you can now perform operations with a more functional piping syntax via %>%. This means that instead of coding this: <

14条回答
  •  感情败类
    2020-11-29 16:48

    There is no need for 3rd party libraries or confusing operator trickery to implement a pipe function - you can get the basics going quite easily yourself.

    Lets start by defining what a pipe function actually is. At its heart, it is just a way to express a series of function calls in logical order, rather than the standard 'inside out' order.

    For example, lets look at these functions:

    def one(value):
      return value
    
    def two(value):
      return 2*value
    
    def three(value):
      return 3*value
    

    Not very interesting, but assume interesting things are happening to value. We want to call them in order, passing the output of each to the next. In vanilla python that would be:

    result = three(two(one(1)))
    

    It is not incredibly readable and for more complex pipelines its gonna get worse. So, here is a simple pipe function which takes an initial argument, and the series of functions to apply it to:

    def pipe(first, *args):
      for fn in args:
        first = fn(first)
      return first
    

    Lets call it:

    result = pipe(1, one, two, three)
    

    That looks like very readable 'pipe' syntax to me :). I don't see how it is any less readable than overloading operators or anything like that. In fact, I would argue that it is more readable python code

    Here is the humble pipe solving the OP's examples:

    from math import sqrt
    from datetime import datetime
    
    def as_date(s):
      return datetime.strptime(s, '%Y-%m-%d')
    
    def as_character(value):
      # Do whatever as.character does
      return value
    
    pipe("2014-01-01", as_date)
    pipe(12, sqrt, lambda x: x**2, as_character)
    

提交回复
热议问题