고급 주제

Python으로 함수 작성하기

Shayne Miel

Software Architect @ Duo Security

중첩 컨텍스트

def copy(src, dst):
  """한 파일의 내용을 다른 파일로 복사합니다.

  Args:
    src (str): 복사할 파일 이름.
    dst (str): 새 파일을 기록할 위치.
  """

# 원본 파일을 열어 내용 읽기 with open(src) as f_src: contents = f_src.read() # 대상 파일을 열어 내용 쓰기 with open(dst, 'w') as f_dst: f_dst.write(contents)
Python으로 함수 작성하기

중첩 컨텍스트

with open('my_file.txt') as my_file:
  for line in my_file:
    # do something
Python으로 함수 작성하기

중첩 컨텍스트

def copy(src, dst):
  """한 파일의 내용을 다른 파일로 복사합니다.

  Args:
    src (str): 복사할 파일 이름.
    dst (str): 새 파일을 기록할 위치.
  """

# 두 파일 모두 열기 with open(src) as f_src: with open(dst, 'w') as f_dst:
# 한 줄씩 읽어 쓰기 for line in f_src: f_dst.write(line)
Python으로 함수 작성하기

에러 처리

def get_printer(ip):
  p = connect_to_printer(ip)

  yield

  # 반드시 호출해야 함. 그렇지 않으면
  # 다른 사용자가 프린터에 연결할 수 없습니다
  p.disconnect()
  print('disconnected from printer')

doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    printer.print_page(doc['txt'])
KeyError: 'txt'
Python으로 함수 작성하기

에러 처리

try:
  # code that might raise an error
except:
  # do something about the error

finally: # this code runs no matter what
Python으로 함수 작성하기

에러 처리

def get_printer(ip):
  p = connect_to_printer(ip)

  try:
    yield
  finally:
    p.disconnect()
    print('disconnected from printer')

doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
disconnected from printer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    printer.print_page(doc['txt'])
KeyError: 'txt'
Python으로 함수 작성하기

컨텍스트 매니저 패턴

Open Close
Lock Release
Change Reset
Enter Exit
Start Stop
Setup Teardown
Connect Disconnect
1 Dave Brondsema의 PyCon 2012 발표에서 수정·발췌: https://youtu.be/cSbD5SKwak0?t=795
Python으로 함수 작성하기

연습해 봅시다!

Python으로 함수 작성하기

Preparing Video For Download...