LoginSignup
4
4

More than 5 years have passed since last update.

letを作ってLet's 1行プログラミング

Posted at

リスト内包記法とか使ってて、なんとしてでも1行で書きたいのに、変数定義したいときってありますよね?はい、こんな感じに書けたらうれしいですよね。

homu.let(lambda mami: (mami[0], mami[1] if len(mami) > 1 else None))

それを半分実現しようという話です。

参考:PythonでLINQライクなリスト処理ライブラリを実装する - TIM Labs

| 演算子をオーバーロードしちゃえば拡張メソッドっぽいことができるということらしいです。同じ方法を使えば let も作れますね!

class let:
    def __init__(self, action):
        self.action = action

    def __ror__(self, source):
        return self.action(source)

そうすると

homu | let(lambda mami: (mami[0], mami[1] if len(mami) > 1 else None))

と書けちゃいます!素敵!

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4