[Python] Icecream 패키지를 사용하여 디버깅하기

2021. 1. 16. 12:18분석 Python/구현 및 자료

728x90

파이썬 코딩을 하다 보면, 모르는 부분에 디버깅 툴이 없다면, print를 해서 찾는 경우가 많다.

필자도 print로 하나하나 하는 습관이 많이 있었지만, 실수가 있기 때문에 디버깅에 어려움을 느낀다.

그래서 어쩌다 찾게된 패키지가 icecream이다.

 

해당 패키지를 사용하게 되면 디버깅 시에는 프린트가 되게 하고, 안될 때에는 전부 다 안되게 할 수 있는 설정이 있다.

아래와 같이 debug시에는 사용하는 모드와 비사용모드를 선택할 수 있기 때문에 항상 프린트를 하고 지우지 않아도 프린트가 안된다라는 장점이 있다. 

from icecream import ic

ic(1)

ic.disable()
ic(2)

ic.enable()
ic(3)

# ic| 1: 1
# ic| 3: 3

 

뿐만 아니라 custom prefix 나 각 들어으는 obj에 따라서 추가적으로 핸들링할 수 있는 것들이 많다.

아래 같은 경우 시간을 prefix로 하는 경우이다.

from datetime import datetime
from icecream import ic 
import time
from datetime import datetime

def time_format():
    return f'{datetime.now()}|> '

ic.configureOutput(prefix=time_format)

for _ in range(3):
    time.sleep(1)
    ic('Hello')

 

아니면 해당 함수가 어디서 호출되는지와 같은 것도 가능하다.

from icecream import ic 

def plus_five(num):
    return num + 5

ic.configureOutput(includeContext=True)
ic(plus_five(4))
ic(plus_five(5))

 

아래는 위에 있는 것들을 사용해서 만들어 본 간단한 예제이다.

 

from icecream import ic as ice_debug
def toString(obj):
#     if isinstance(obj, str):
#         return '[!string %r with length %i!]' % (obj, len(obj))
    if isinstance(obj, (int,float)):
        return '[!%r %r is greater than zero %r!]' % (type(obj) , obj , obj > 0)
    elif isinstance(obj, (np.ndarray)):
        return '[!array %r dim %r]' % (obj , obj.shape)
    elif isinstance(obj, (pd.DataFrame)):
        return '[!dataframe %r dim %r]' % (obj , obj.shape)
    elif isinstance(obj, (list)):
        return '[!list %r dim %r]' % (obj , len(obj))
    return repr(obj)
ice_debug.configureOutput(prefix='##debug(base) ->')
ice_debug.configureOutput(argToStringFunction=toString)

 

 

github.com/gruns/icecream

 

gruns/icecream

🍦 Never use print() to debug again. Contribute to gruns/icecream development by creating an account on GitHub.

github.com

 

towardsdatascience.com/stop-using-print-to-debug-in-python-use-icecream-instead-79e17b963fcc

 

Stop Using Print to Debug in Python. Use Icecream Instead

Are you Using Print or Log to Debug your Code? Use Icecream instead.

towardsdatascience.com

 

728x90