หัวข้อขั้นสูง

การเขียนฟังก์ชันใน Python

Shayne Miel

Software Architect @ Duo Security

Context ซ้อนกัน

def copy(src, dst):
  """Copy the contents of one file to another.

  Args:
    src (str): File name of the file to be copied.
    dst (str): Where to write the new file.
  """

# Open the source file and read in the contents with open(src) as f_src: contents = f_src.read() # Open the destination file and write out the contents with open(dst, 'w') as f_dst: f_dst.write(contents)
การเขียนฟังก์ชันใน Python

Context ซ้อนกัน

with open('my_file.txt') as my_file:
  for line in my_file:
    # do something
การเขียนฟังก์ชันใน Python

Context ซ้อนกัน

def copy(src, dst):
  """Copy the contents of one file to another.

  Args:
    src (str): File name of the file to be copied.
    dst (str): Where to write the new file.
  """

# Open both files with open(src) as f_src: with open(dst, 'w') as f_dst:
# Read and write each line, one at a time for line in f_src: f_dst.write(line)
การเขียนฟังก์ชันใน Python

การจัดการข้อผิดพลาด

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

  yield

  # This MUST be called or no one else will
  # be able to connect to the printer
  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

รูปแบบของ context manager

เปิด ปิด
ล็อก ปลดล็อก
เปลี่ยน รีเซ็ต
เข้า ออก
เริ่ม หยุด
ตั้งค่า ล้างค่า
เชื่อมต่อ ตัดการเชื่อมต่อ
1 ดัดแปลงจากการบรรยายของ Dave Brondsema ใน PyCon 2012: https://youtu.be/cSbD5SKwak0?t=795
การเขียนฟังก์ชันใน Python

มาฝึกกันเถอะ!

การเขียนฟังก์ชันใน Python

Preparing Video For Download...