英文:
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} y
与y(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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论