有关Python中的管道操作符是否有任何PEP?

huangapple go评论63阅读模式
英文:

Is there any PEP regarding a pipe operator in Python?

问题

这种类型的Python代码通常如下:

def load_data():
   df_ans = get_data()
   df_checked = check_data(df_ans) # 返回df_ans或引发错误
   return_dict = format_data(df_ans) 
   return return_dict

也可以这样编写上面的代码(但我认为这种写法不够美观):

def load_data():
   return format_data(check_data(get_data()))

如果这都是Pandas代码,可以使用.pipe方法来执行如下操作:

def load_data():
   return get_data().pipe(check_data).pipe(format_data)

然而,在Python中似乎没有通用的方法来“pipe”操作,类似于:

def load_data():
   return (get_data() |> check_data |> format_data)

关于这个问题是否有PEP提案,我未能找到相关的PEP提案。

我看到一些库对|进行了运算符重载,但我认为这不是我正在寻找的 - 我正在寻找x {operator} yy(x)是相同的(当然需要y是可调用的)。

英文:

It is often common to write this type of python code:

def load_data():
   df_ans = get_data()
   df_checked = check_data(df_ans) # returns df_ans or raises an error
   return_dict = format_data(df_ans) 
   return return_dict

One could write the above like this (but it's ugly in my opinion)

def load_data():
   return format_data(check_data(get_data()))

If this were all pandas code, one could use the .pipe method to do as follows:

def load_data():
   return get_data().pipe(check_data).pipe(format_data)

However, there seems to be no universal way to "pipe" things in Python, something like:

def load_data():
   return (get_data() |> check_data |> format_data)

Is there any PEP proposal for this? I could not find one.

I've seen some libraries that do operator overloading on | but I don't think that's what I'm looking for - I'm looking for x {operator} y to be the same as y(x) (which of course requires y to be callable)

答案1

得分: 1

我不认为Python中的管道运算符会在不久的将来得到批准。要执行该操作,已经有了toolz库中的pipe函数。它不是Python内置库,但被广泛使用。

如果你感兴趣,这是它的实现:

def pipe(data, *funcs):
    for func in funcs:
        data = func(data)
    return data
英文:

I don't think a pipe operator in Python will be approved in the near future. To do that operation there is already the function pipe in the toolz library.
It is not a Python built in library but is widely used.

In case you are curious the implementation is just:

def pipe(data, *funcs):
    for func in funcs:
        data = func(data)
    return data

huangapple
  • 本文由 发表于 2023年3月15日 20:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定