๐Ÿ Python Walrus Operator

Contents

๊ฐœ์š”

ํŒŒ์ด์ฌ 3.8 ๋ฒ„์ „๋ถ€ํ„ฐ ์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๋Š” :=์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋Š”๋ฐ, ์ƒ๊น€์ƒˆ๊ฐ€ ๋งˆ์น˜ ๋ฐ”๋‹ค์ฝ”๋ผ๋ฆฌ์˜ ๋ˆˆ๊ณผ ์—„๋‹ˆ๋ฅผ ๋‹ฎ์•˜๋‹คํ•˜์—ฌ ์ด๋ฆ„์ด ๋ถ™์—ฌ์กŒ๋‹ค๊ณ  ํ•œ๋‹ค. (๊ท€์—ฌ์›Œ..)

ํ•„์ž๋Š” ํŒŒ์ด์ฌ ์ฝ”๋”ฉ์˜ ๊ธฐ์ˆ  ์ฑ…์„ ์ฝ๊ณ  ์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž์— ๋Œ€ํ•ด ์•Œ๊ฒŒ ๋˜์—ˆ๋Š”๋ฐ, ์ง„์ฆ‰ ์•Œ์•˜๋”๋ผ๋ฉด ๋งŽ์€ ์ฝ”๋“œ๋ฅผ ์ข€ ๋” ํด๋ฆฐํ•˜๊ฒŒ ์งค ์ˆ˜ ์žˆ์ง€ ์•Š์•˜์„๊นŒ ์ƒ๊ฐ๋œ๋‹ค.

์™ˆ๋Ÿฌ์Šค(walrus) ์—ฐ์‚ฐ์ž๋ž€?

์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๋Š” ๋Œ€์ž…์‹์ด๋ผ๊ณ ๋„ ๋ถ€๋ฅด๋Š”๋ฐ ์ด๋Š” ๋Œ€์ž…๋ฌธ์ด ์“ฐ์ผ ์ˆ˜ ์—†๋Š” ์œ„์น˜์—์„œ ๋ณ€์ˆ˜์— ๊ฐ’์„ ๋Œ€์ž…ํ•  ์ˆ˜ ์žˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค๋ฉด if๋ฌธ ์•ˆ์— ๋Œ€์ž…์‹์„ ์“ธ ์ˆ˜ ์žˆ๋‹ค.

์˜ˆ์‹œ

์‰ฌ์šด ์˜ˆ์‹œ๋กœ a๋ผ๋Š” ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๊ฐ€ 10 ์ด์ƒ์ด๋ฉด ๊ธธ์ด์™€ ํ•จ๊ป˜ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋„ˆ๋ฌด ๊ธธ๋‹ค๋Š” ๋ฌธ์žฅ์„ ์ถœ๋ ฅํ•˜๋„๋ก ํ•ด๋ณด์ž.

if len(a) > 10:
    print(f"List is too long ({len(a)} elements, expected <= 10)")

len(a)์„ ๋‘ ๋ฒˆ ๊ณ„์‚ฐํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์™ ์ง€ ๋ณ€์ˆ˜์— ๋‹ด์•„์ฃผ๊ณ  ์‹ถ์€ ๋งˆ์Œ์ด ๋“ ๋‹ค.

n = len(a)
if n:
    print(f"List is too long ({n} elements, expected <= 10)")

์ข€ ๋” ๊น”๋”ํ•ด์กŒ์ง€๋งŒ n์€ if๋ฌธ ์•ˆ์—์„œ๋งŒ ์“ฐ์ด๋Š”๋ฐ, ์ด๋ฅผ if๋ฌธ ์•ž์—์„œ ์„ ์–ธ์„ ํ•ด์ฃผ๋‹ˆ ๋Œ€๋‹จํžˆ ์ค‘์š”ํ•œ ๋ณ€์ˆ˜์ฒ˜๋Ÿผ ๋ณด์ธ๋‹ค.

์ด๋Ÿด ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์—ฐ์‚ฐ์ž๊ฐ€ ๋ฐ”๋กœ ๋ฐ”๋‹ค ์ฝ”๋ผ๋ฆฌ ์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž์ด๋‹ค.

์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด if๋ฌธ ์•ˆ์—์„œ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ณ  ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

์™€์šฐ! ํ›จ์”ฌ ๊น”๋”ํ•ด์กŒ๋‹ค.

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ •๊ทœ์‹์„ ๋‹ค๋ฃฐ ๋•Œ๋„ ์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๊ฐ€ ์žˆ์œผ๋ฉด ๋ฐ˜๋ณต์„ ํ”ผํ•  ์ˆ˜ ์žˆ๋‹ค.

discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
    discount = float(mo.group(1)) / 100.0

loop ์ข…๋ฃŒ๋ฅผ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ’์„ ๊ณ„์‚ฐํ•œ ๋‹ค์Œ loop์—์„œ ๋™์ผํ•œ ๊ฐ’์„ ๋‹ค์‹œ ํ•„์š”๋กœ ํ•˜๋Š” while loop์—๋„ ์œ ์šฉํ•˜๊ฒŒ ์“ฐ์ธ๋‹ค.

while (block := f.read(256)) != '':
    process(block)

๋ฆฌ์ŠคํŠธ ์ปดํ”„๋ฆฌํ—จ์…˜์—์„œ ํ•„ํ„ฐ๋ง์„ ํ•˜๋Š” ๊ฒฝ์šฐ์—๋„ ์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

[clean_name.title() for name in names
 if (clean_name := normalize('NFC', name)) in allowed_names]

๋งˆ๋ฌด๋ฆฌ

์™ˆ๋Ÿฌ์Šค ์—ฐ์‚ฐ์ž๋ฅผ ์•Œ๊ณ  ๋‚˜๋‹ˆ ๊ณ ์น  ์ˆ˜ ์žˆ๋Š” ์ฝ”๋“œ๊ฐ€ ๋งŽ์ด ๋ณด์ธ๋‹ค.

๊ฐ„๋‹จํ•˜์ง€๋งŒ ํ™œ์šฉํ•˜๊ธฐ ์ข‹์€ ๊ฐœ๋…๋“ค์„ ์•Œ๊ฒŒ ๋˜๋ฉด ๊ธฐ๋ถ„์ด ์ข‹๋‹ค.

์ ์–ด๋„ ๊พธ์ค€ํžˆ ์‚ฌ์šฉํ•  ์–ธ์–ด์™€ ํ”„๋ ˆ์ž„์›Œํฌ๋“ค์€ ์—…๋ฐ์ดํŠธ ๋…ธํŠธ๋ฅผ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ™•์ธํ•ด์•ผ๊ฒ ๋‹จ ์ƒ๊ฐ์ด ๋“ ๋‹ค.

References


Written by@ugaemi
Record things I want to remember

๐Ÿฑ GitHub๐Ÿ“š Reading Space