python toolz - 组合方法(与函数相反)

joe*_*mct 2 python toolz

在toolz项目中,有没有办法像函数一样对待对象方法,这样我就可以更好地进行组合、柯里化等?
我所说的更好是指可读性和类似的性能

这是一个简单的例子:

# given a list strings (names),
l = ["Harry"  ,
    "Sally  "    ,
    " bEn " ,
    " feDDy "  ]

# Lets pretend I want to apply a few simple string methods on each item in the
# list (This is just an example), and maybe replace as it's multi-airity.

# Traditional python list comprehension:
print([x.strip().lower().title().replace('H','T') for x in l ])

['Tarry', 'Sally', 'Ben', 'Feddy']

# my attempt, at toolz, same question with compose, curry,
# functools.partial.

from toolz.functoolz import pipe, thread_last
thread_last(l,
            (map , str.strip),
            (map , str.lower),
            (map , str.title),
            (map , lambda x: x.replace('H','T')), # any better way to do this?
            # I wish i had function/method `str.replace(__init_value__, 'H', 'T')` where the
            # `__init_value` is what I guess would go to the str constructor?
            list,
            print)
Run Code Online (Sandbox Code Playgroud)

我不喜欢所有额外的 lambda...并且我无法想象这对于性能来说是可以的。关于如何使用 toolz 改善这一点有什么建议吗?

有了这个operators模块,我可以让大多数操作员不那么痛苦,并省略 lambda 表达式来进行加法、减法等操作。

最近版本的 python 中是否有类似的方法调用?

900*_*000 5

注意,x.replace(y, z)确实是str.replace(x, y, z)。您可以使用partial经常使用的特定替代品。

这同样适用于其余的方法:如果通过类访问方法,它是未绑定的,并且第一个参数 ( self) 是函数的普通参数。周围没有魔法。(实例方法被部分应用,将它们的self值锁定到实例。)

因此,我冒险thread_last(l, (map, pipe(str.strip, str.lower, str.title))对每个字符串元素应用三个函数。

(如果您对 Python 中的 FP 感兴趣,请查看http://coconut-lang.org/

  • 构造函数(或者更确切地说,“__new__”)所做的魔力之一就是每个方法都具有“instance.foo =partial(cls​​.foo, instance)”之类的东西。您可以使用“__metaclass__”协议覆盖您的类和实例创建;阅读它,它很有趣,并且揭示了大部分内在的“魔力”。 (2认同)