以下の内容はhttps://blog.kyanny.me/entry/2021/08/29/040610より取得しました。


Python 3.8 以降で Ruby の if m = "foo".match(/foo/) みたいに if の条件の結果を代入するには if m:= xxx とする

Ruby で書くとき、非常によく使う syntax の一つ。

str = open('/etc/hosts').read
if m = str.match(/local/)
  puts m[0]
end
❯ ruby if-assignment-in-conditional.rb
local

正式名称がわからず、検索に苦労したが、assignment in a conditional clause などと呼ぶらしい。

Python で同じ書き方をすると syntax error になる。

import re
with open('/etc/hosts') as f:
  if m = re.search(r'local', f.read()):
    print(m[0])
❯ python3 if-assignment-in-conditional.py
  File "if-assignment-in-conditional.py", line 3
    if m = re.search(r'local', f.read()):
         ^
SyntaxError: invalid syntax

Python 3.8 からは、似てるけどちょっと違う syntax で同様のことができるようになったらしい。こちらは正式(公式)な呼び名があって、Assignment Expression と呼ぶらしい。

python - Can we have assignment in a condition? - Stack Overflow

PEP 572 -- Assignment Expressions | Python.org

import re
with open('/etc/hosts') as f:
  if m := re.search(r'local', f.read()):
    print(m[0])
❯ python3 if-assignment-in-conditional-3.8.py
local



以上の内容はhttps://blog.kyanny.me/entry/2021/08/29/040610より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14