파이썬 코딩을 더 깔끔하게! #9

Dunno·2021년 7월 4일
1

Better Way 10. 대입식을 사용해 반복을 피하라

왈러스 연산자

대입식(assignment expression)이라고 부르며 파이썬 언어에서 고질적인 코드 중복문제를 해결하고자 도입된 구문이다.
대입문이 쓰일 수 없는 위치에서 변수에 값을 대입할 수 있으므로 유용하다.
ex) if문의 조건식 안

! 왈러스 연산자는 파이썬 3.8버전 이후부터 사용할 수 있습니다. !

재사용이 불필요한 변수인 경우

count변수는 오직 비교를 위해서만 사용해야 하는 경우에 사용되면 좋다.
if식에는 비교문만 사용할 수 있고, 대입을 할 수 없다.
그러므로 if문 밖에서 조건 비교용 변수를 선언하지 않고 안에서 바로 사용이 가능하다.

일반 대입문

fresh_fruits = {
	'사과': 10,
  	'바나나': 8,
  	'레몬': 5,
}

def make_lemonade(count):
	...
    
def out_of_stock():
	...
#-------------------------------------------------------------#
count = fresh_fruit.get('레몬', 0)
if count:
  make_lemonade(count)
else:
  out_of_stock()

왈러스 연산자

if count := fresh_fruit.get('레몬', 0):
	make_lemonade(count)
else:
	out_of_stock()
  • 위와 같이 count가 if문의 첫 번째 블록에서만 의미가 있다는 점이 명확하게 보이기 때문에 코드를 읽기가 더 쉽다.

  • 왈러스 연산자는 count에 대입후 if문을 통해 평가한다.

현재 관심 영역을 둘러싼 변수의 경우

if문 안에서 대입을 하기 때문에 의미가 명확해진다.
if 밖에서 선언된 변수의 경우는 if식만 보고 이 변수가 무슨 의미인지 파악하기 힘들다
if 안에서 바로 대입을 하기 때문에 의미가 보다 명확해진다.

일반 대입문

def make_cider(count):
	...
    
count = fresh_fruit.get('사과', 0)
if count >= 4:
	make_cider(count)
else:
	out_of_stock()

왈러스 연산자

if (count := fresh_fruit.get('사과', 0)) >= 4:
	make_cider(count)
else:
	out_of_stock()
#------------------------------------------------------------------#
pieces = 0
if (count := fresh_fruit.get('바나나', 0)) >= 2:
	pieces = slice_bananas(count)

try:
	smoothies = make_smoothies(pieces)
except OutOfBananas:
	out_of_stock()

Switch/Case문 모사의 경우

Python에서는 Switch/Case문을 사용할 수 없다.

  • C/C++의 Switch/Case문 예시
char input= 'A';
switch(input){
    case 'A' : 
        printf("input의 값은 A입니다.");
        break;
    case 'B' : 
        printf("input의 값은 B입니다.");
        break;  
    default :    
        printf("input의 값은 A과B가 아닌 다른 문자입니다.");
}

일반 대입문

일반 대입문을 사용할 경우 다음과 같이 if/else문이 매우 길어지고 가독성도 떨어진다.

if count >= 2:
    pieces = slice_bananas(count)
    to_enjoy = make_smoothies(pieces)
else:
    count = fresh_fruit.get('사과', 0)
    if count >= 4:
        to_enjoy = make_cider(count)
    else:
        count = fresh_fruit.get('레몬', 0)
        if count:
            to_enjoy = make_lemonade(count)
        else:
            to_enjoy = '아무것도 없음'

왈러스 연산자

왈러스 연산자를 통해 switch/case문을 비슷하게 흉내낼 수 있다.

if (count := fresh_fruit.get('바나나',0)) >= 2 :  # 대입식
  pieces = slice_bananas(count)
  to_enjoy = make_smoothies(pieces)
elif (count := fresh_fruit.get('사과',0)) >= 4 :
  to_enjoy = make_cider(count)
elif (count := fresh_fruit.get('레몬',0)) :
  to_enjoy = make_lemonade(count)
else:
  to_enjoy = 'nothing'

Do/While문 모사의 경우

Python에서는 Do/While문을 사용할 수 없다.

  • Do/While문
    do 안의 실행문이 처음에 한번은 무조건 실행된다
    while 뒤에 조건문을 체크해서 참이면 do를 다시 수행하고, 거짓이면 그대로 반복을 종료한다.
int ia=1, isum=0;
do {
   isum += ia;
} while(ia++ < 100);

일반 대입문

bottles = []
while True:
	fresh_fruit = pick_fruit()
    if not fresh_fruit:
    	break
     
    for fruit, count in fresh_fruit.items():
    	batch = make_juice(fruit, count)
        bottles.extend(batch)

왈러스 연산자

bottels = []
while fresh_fruit := pick_fruit():
	for fruit, count in fresh_fruit.items():
    	batch = make_juice(fruit, count)
        bottles.extend(batch)

Python에서는 왈러스 연산자를 통해 while 조건을 체크할 때 마다 대입식으로 조건을 업데이트 한 후 체크할 수 있다.

0개의 댓글