표현식의 일부 값을 변수에 대입하는 문법이다.
바다코끼리 연산자라고도 불리며 Python 3.8에 추가되었다.
:=
을 통해 사용한다.
대입 연산자 사용 전
string = "hello world"
if string.index("world") > 3:
print(string.index("world"))
6
대입 연산자 사용 후
string = "hello world"
if (world_index := string.index("world")) > 3:
print(world_index)
6
가독성이 훨신 좋다.
def f():
print("호출됨")
return 5
if f() > 2:
print(f())
호출됨
호출됨
5
대입 연산자 사용 후
def f():
print("호출됨")
return 5
if (x:=f()) > 2:
print(x)
호출됨
5
함수 호출을 줄일 수 있는 면에서 성능도 뛰어나다.
대입 연산자의 우선순위는 다른 연산자보다 낮다.
그러니 사용에 주의해야 한다.
if (x := 5) > 2:
print(x)
if x := 5 > 2: # 5 > 2 우선 연산
print(x)
5
True
https://docs.python.org/ko/3/whatsnew/3.8.html
(CPython Grammar 보다 찾음)