■ はじめに
小ネタ。 Python で「:=」って出てきて、 これなんだ?ってなったので、メモ。
目次
【1】ウォルラス演算子 (:=) 1)補足情報 2)何故、Walrus(セイウチ)? 【2】サンプル 1)NG: Syntax Error 2)OK: 「:=」を使った場合
【1】ウォルラス演算子 (:=)
* := を用いることで代入の結果を式として評価することが可能 => 言葉より下のサンプルを見た方が早い => 以下のサンプルのように、ウォルラス演算子 (:=)により一行で書ける => resultにも値が入っている
サンプル
def is_hello_world(value: str) -> bool: return "hello world" in value.lower() # 通常の書き方 # result = is_hello_world("Hello world!!") # if result: if result := is_hello_world("Hello world!!"): # ウォルラス演算子 (:=)により一行で書ける print(f"This is Hello world - {result}.") # This is Hello world - True. (resultにも値が入っている) else: print(f"This is not Hello world - {result}.")
1)補足情報
* From Python 3.8 * Walrus operator (cf. Walrus = セイウチ) * PEP 572: 代入式 (assignment expression)
https://peps.python.org/pep-0572/#relative-precedence-of
2)何故、Walrus(セイウチ)?
https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
日本語訳
より大きな式の一部として変数に値を代入する新しい構文:=がある セイウチの目と牙に似ていることから、「セイウチ演算子」として 親しまれている。
【2】サンプル
1)NG: Syntax Error
value = "Hello World!!" # Error if (length = len(value)) > 5: print(f'{length} > 5') else: print(f'{length} <= 5')
2)OK: 「:=」を使った場合
value = "Hello World!!" if (length := len(value)) > 5: print(f'{length} > 5') else: print(f'{length} <= 5')
参考文献
https://qiita.com/Yu_unI1/items/3bfcd1b0fbe12ea2dda9
https://www.tohoho-web.com/python/operators.html#assignment-expression
https://www.lifewithpython.com/2019/10/python-walrus-operator-assignment-expression.html
https://zenn.dev/spacemarket/articles/0b2102f35c28e9
関連記事
Python ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/08/07/231242
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / 文字列操作 ~
https://dk521123.hatenablog.com/entry/2023/10/20/000000
Python ~ 基本編 / 日付・日時あれこれ ~
https://dk521123.hatenablog.com/entry/2022/02/01/000000
Python ~ 基本編 / 正規表現 ~
https://dk521123.hatenablog.com/entry/2019/09/01/000000
Python ~ 基本編 / 正規表現あれこれ ~
https://dk521123.hatenablog.com/entry/2020/10/15/000000
Python ~ 基本編 / map ~
https://dk521123.hatenablog.com/entry/2021/03/29/000000
Python ~ 基本編 / リスト・タプル・辞書・集合 ~
https://dk521123.hatenablog.com/entry/2019/10/12/084943
Python ~ namedtuple / 簡易クラス ~
https://dk521123.hatenablog.com/entry/2020/11/10/134233
Python ~ 基本編 / 制御文 ~
https://dk521123.hatenablog.com/entry/2019/08/25/000330
Python ~ 基本編 / ラムダ lambda ~
https://dk521123.hatenablog.com/entry/2019/09/23/000000
Python ~ JSONあれこれ ~
https://dk521123.hatenablog.com/entry/2022/02/14/000000