Is it a good idea to have a syntax sugar to function composition in Python?

后端 未结 4 684
我寻月下人不归
我寻月下人不归 2021-02-05 08:37

Some time ago I looked over Haskell docs and found it\'s functional composition operator really nice. So I\'ve implemented this tiny decorator:

from functools im         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 09:17

    I don't have enough experience with Python to have a view on whether a language change would be worthwhile. But I wanted to describe the options available with the current language.

    To avoid creating unexpected behavior, functional composition should ideally follow the standard math (or Haskell) order of operations, i.e., f ∘ g ∘ h should mean apply h, then g, then f.

    If you want to use an existing operator in Python, say <<, as you mention you'd have a problem with lambdas and built-ins. You can make your life easier by defining the reflected version __rlshift__ in addition to __lshift__. With that, lambda/built-ins adjacent to composable objects would be taken care of. When you do have two adjacent lambda/built-ins, you'll need to explicitly convert (just one of) them with composable, as @si14 suggested. Note I really mean __rlshift__, not __rshift__; in fact, I would advise against using __rshift__ at all, since the order change is confusing despite the directional hint provided by the shape of the operator.

    But there's another approach that you may want to consider. Ferdinand Jamitzky has a great recipe for defining pseudo infix operators in Python that work even on built-ins. With this, you can write f |o| g for function composition, which actually looks very reasonable.

提交回复
热议问题