LoginSignup
0
1

More than 3 years have passed since last update.

PEP 572, Assignment expressions

Last updated at Posted at 2019-10-11

最近、Pythonの新たな実装追っかけを怠っていたので、この時間でお勉強してみた。
吉祥寺でゆるく仕事帰りの勉強会をやっていて、そこで調べたことを記録したノートです。
https://kichipy.connpass.com/event/149625/

PEP 572, Assignment expressionsについて

参考 syntax-and-assignment-expressions-what-and-why

:= という表記のAssignment expressions(代入演算子と言ったら良いのかな)が追加されました。例えば、 ifwhile の条件式の条件内で、変数に値を代入しながら処理を実行したりする時に使うと良さげです。

まずは、、、、

if statement(if条件式)

今まで

match = pattern.match(line)
if match:
    return match.group(1)

Assignment expressions(代入演算)にすると

if match := pattern.match(line):
    return match.group(1)

Infinite while statement(whileの条件式)

今まで:

while True:
    data = f.read(1024)
    if not data:
        break
    use(data)

Assignment expressions(代入演算)にすると

while data := f.read(1024):
    use(data)

だいぶコードがシンプルに書けることがわかります。
こんな処理は実際書くことを無いのですが、動作のおさらい。

>>> if a := None:  # a に None を代入して、a を評価
...     print(a)
...
>>> if a := 1:  # a に 1 を代入して、a を評価
...     print(a)
...
1

その他stackoverflowに上がっていた例

stuff = [(lambda y: [y,x/y])(f(x)) for x in range(5)]

stuff = [[y := f(x), x/y] for x in range(5)]

こうなります。読みにくい lambda を使わなくてよいので、いい感じです。

inputを以下様に処理もできます。

command = input("> ")
while command != "quit":
    print("You entered:", command)
    command = input("> ")

while (command := input("> ")) != "quit":
    print("You entered:", command)

なります。

感想

実践でも使い所は結構ありそうなのと、そこまで可読性が下がる印象はないので、積極的に使っていこうかなと思った次第。

0
1
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
0
1