2-4. Context Manager (1)

uoayopΒ·2021λ…„ 3μ›” 14일
0

Leaf와 Python

λͺ©λ‘ 보기
8/21
post-thumbnail

이번 κ°•μ˜λŠ” μ•žμ— λ°°μ› λ˜ ν•„μˆ˜ 문법듀이 발판이 λ˜μ–΄μ€„ 것이닀.
μ‘°κΈˆμ€ μƒμ†Œν•˜μ§€λ§Œ ν•œλ²ˆμ―€μ€ 듀어봐야 ν•  λ‚΄μš©μ΄λ‹ˆ 눈 크게 뜨고 ν•œλ²ˆ 보자!

특히 언더바(__ ) λ‘κ°œλ‘œ μ‹œμž‘ν•˜λŠ” λ§€μ§λ©”μ†Œλ“œλŠ” κ·Έλ™μ•ˆ 눈 마주치면 λ°”λ‘œ μ€„ν–‰λž‘ μ³€μ—ˆλŠ”λ° μ˜€λŠ˜μ€ λˆˆμ‹Έμ›€ μ’€ 해봐야겠닀~! πŸ‘€

νŒŒμΌμ„ μ˜€ν”ˆν•  λ•Œ μ“°λŠ” with 문도 써보긴 ν–ˆμ§€λ§Œ 이해λ₯Ό ν•΄μ„œ μ“°κΈ°λ³΄λ‹€λŠ” λ³΅λΆ™ν•΄μ„œ μ“°κΈ° κΈ‰κΈ‰ν–ˆλ˜ 것 κ°™λ‹€. 였늘 함 λΆ™μž~..

context manager

  • 였늘의 ν‚€μ›Œλ“œ
    • Contextlib, __enter__, __exit__, with κΈ°λŠ₯ 직접 κ΅¬ν˜„

context manager?

cm은 μ›ν•˜λŠ” 타이밍에 μ •ν™•ν•˜κ²Œ λ¦¬μ†ŒμŠ€λ₯Ό ν• λ‹Ή, 제곡, λ°˜ν™˜ν•˜λŠ” 역할을 ν•΄μ€€λ‹€.
κ°€μž₯ λŒ€ν‘œμ μΈ with ꡬ문을 이해할 수 μžˆμ–΄μ•Όν•œλ‹€.

try-finallyλ₯Ό μ΄μš©ν•œ cm

  • with ꡬ문이 λ‚˜μ˜€κΈ° μ „μ—” νŒŒμΌμ„ μ—΄κ³  닫을 λ•Œ, closeλ₯Ό 톡해 직접 μžμ› ν• λ‹Ή ν•΄μ œλ₯Ό ν•΄μ€˜μ•Ό ν–ˆλ‹€.
file = open('./testfile1.txt','w')
try:
    file.write('context manager test1\ncontextllib test1.')
finally:
    file.close()

with문을 μ΄μš©ν•œ cm

  • with 문은 ꡳ이 close 해주지 μ•Šμ•„λ„ μ•Œμ•„μ„œ μžμ› μ‚¬μš©μ„ μ’…λ£Œν•΄μ€€λ‹€.
with open('./testfile2.txt','w') as f:
    f.write('context manager test2\ncontextllib test2.')
  • 파이썬 λ‚΄λΆ€μ μœΌλ‘œ withλ¬Έ μ•ˆμ— close와 κ΄€λ ¨ λ‚΄μš©μ΄ μ •μ˜λ˜μ–΄ μžˆλ‹€.
    κ·Έ 내뢀적인 ꡬ쑰λ₯Ό 쑰금만 μˆ˜μ •ν•΄μ„œ 우리만의 with문으둜 μ»€μŠ€ν„°λ§ˆμ΄μ¦ˆ ν•΄λ³΄μž!

cm μ •μ˜ν•΄λ³΄κΈ°

  • μš°μ„  classλ₯Ό λ”°λ‘œ μ •μ˜ν•΄μ„œ νŒŒμΌμ„ μ—΄κ³  닫을 λ•Œ λ°œμƒν•˜λŠ” 상황을 μ •μ˜ν•΄μ€„ 것이닀.
  1. __init__ λ©”μ†Œλ“œλŠ” ν΄λž˜μŠ€κ°€ μ •μ˜λ  λ•Œ μžλ™μœΌλ‘œ μ‹€ν–‰λœλ‹€.
    파일 이름과 μ–΄λ–€ λ©”μ†Œλ“œλ₯Ό μ‹€ν–‰ν•  지λ₯Ό 인자둜 λ°›μ•„μ£Όμ—ˆλ‹€.
class MyFileWrite():
    def __init__(self,file_name, method):
        print('myFileWrite started : __init__')
        # file.obj = open ν•¨μˆ˜
        self.file_obj = open(file_name,method)
  1. __enter__ λ©”μ†Œλ“œλŠ” with ꡬ문에 μ§„μž…ν•  λ•Œ μžλ™μœΌλ‘œ ν˜ΈμΆœλœλ‹€.
    def __enter__(self):
            print('MyFileWrite started : __enter__')
            return self.file_obj
  1. __exit__ λ©”μ†Œλ“œλŠ” with ꡬ문을 λΉ μ Έλ‚˜κ°€κΈ° 직전에 μ‹€ν–‰λœλ‹€.
    μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œμ˜ 정보듀을 μΈμžμ— λ‹΄μ•„μ„œ λ¦¬ν„΄ν•œλ‹€.

    exc_type : μ˜ˆμ™Έ νƒ€μž…
    value: 였λ₯˜μ˜ λ‚΄μš©
    trace_back : 였λ₯˜λ₯Ό λ°œμƒμ‹œν‚¨ ν•¨μˆ˜ ν˜ΈμΆœμ„ μ—­μΆ”μ ν•œ λ‚΄μš©

     def __exit__(self, exc_type, value, trace_back):
            print('MyFileWrite started : __exit__')
            if exc_type:
                # μ˜ˆμ™Έ λ°œμƒ μ‹œ 싀행됨 - customize κ°€λŠ₯함
                print('Logging exception {}'.format(exc_type, value, trace_back))
            self.file_obj.close()
  • 전체 μ½”λ“œ
class MyFileWrite():
    def __init__(self,file_name, method):
        print('myFileWrite started : __init__')
        # file.obj = open ν•¨μˆ˜
        self.file_obj = open(file_name,method)

    def __enter__(self):
        print('MyFileWrite started : __enter__')
        return self.file_obj
    
    def __exit__(self, exc_type, value, trace_back):
        print('MyFileWrite started : __exit__')
        if exc_type:
            print('Logging exception {}'.format(exc_type, value, trace_back))
        self.file_obj.close()

with MyFileWrite('./testfile3.txt','w') as f:
    f.write('context manager test3\ncontextllib test3.')

좜처: μΈν”„λŸ° - λͺ¨λ‘λ₯Ό μœ„ν•œ 파이썬 : ν•„μˆ˜ 문법 배우기 Feat. μ˜€ν”ˆμ†ŒμŠ€ νŒ¨ν‚€μ§€ 배포 (Inflearn Original)

profile
slow and steady wins the race 🐒

0개의 λŒ“κΈ€