İleri konular

Python'da Fonksiyon Yazımı

Shayne Miel

Software Architect @ Duo Security

İç içe bağlamlar

def copy(src, dst):
  """Bir dosyanın içeriğini diğerine kopyalar.

  Args:
    src (str): Kopyalanacak dosyanın adı.
    dst (str): Yeni dosyanın yazılacağı yer.
  """

# Kaynak dosyayı aç ve içeriği oku with open(src) as f_src: contents = f_src.read() # Hedef dosyayı aç ve içeriği yaz with open(dst, 'w') as f_dst: f_dst.write(contents)
Python'da Fonksiyon Yazımı

İç içe bağlamlar

with open('my_file.txt') as my_file:
  for line in my_file:
    # do something
Python'da Fonksiyon Yazımı

İç içe bağlamlar

def copy(src, dst):
  """Bir dosyanın içeriğini diğerine kopyalar.

  Args:
    src (str): Kopyalanacak dosyanın adı.
    dst (str): Yeni dosyanın yazılacağı yer.
  """

# Her iki dosyayı aç with open(src) as f_src: with open(dst, 'w') as f_dst:
# Satır satır oku ve yaz for line in f_src: f_dst.write(line)
Python'da Fonksiyon Yazımı

Hata yönetimi

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

  yield

  # Bu MUTLAKA çağrılmalı, yoksa
  # başka kimse yazıcıya bağlanamaz
  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'da Fonksiyon Yazımı

Hata yönetimi

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

finally: # this code runs no matter what
Python'da Fonksiyon Yazımı

Hata yönetimi

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'da Fonksiyon Yazımı

Bağlam yöneticisi kalıpları

Kapat
Kilitle Serbest bırak
Değiştir Sıfırla
Gir Çık
Başlat Durdur
Kurulum Söküm
Bağlan Bağlantıyı kes
1 PyCon 2012’de Dave Brondsema’nın konuşmasından uyarlanmıştır: https://youtu.be/cSbD5SKwak0?t=795
Python'da Fonksiyon Yazımı

Hadi pratik yapalım!

Python'da Fonksiyon Yazımı

Preparing Video For Download...