<jupyter_start><jupyter_text>Context Managers and with Blocks<jupyter_code>with open('clockdeco.py') as fp:
    src = fp.read(60)
len(src)
fp
fp.closed, fp.encoding
fp.read(60)
from mirror import LookingGlass
with LookingGlass() as what:
    print('Alice, Kitty and Snowdrop')
    print(what)
from mirror import LookingGlass
manager = LookingGlass()
manager
monster = manager.__enter__()
monster == 'JABBERWOCKY'
monster
manager
manager.__exit__(None, None, None)
monster<jupyter_output><empty_output><jupyter_text>Using @contextmanager<jupyter_code># from mirror_gen import looking_glass
# with looking_glass() as what:
#     print('Alice, Kitty and Snowdrop')
#     print(what)
import contextlib

@contextlib.contextmanager
def looking_glass():
    import sys
    original_write = sys.stdout.write
    
    def reverse_write(text):
        original_write(text[::-1])
        
    sys.stdout.write = reverse_write
    msg = ''
    try:
        yield 'JABBERWOCKY'
    except ZeroDivisionError:
        msg = 'Please DO NOT divice by zero!'
    finally:
        sys.stdout.write = original_write
        if msg:
            print(msg)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09965635738831616, 'fraction_numerical': 0.00429553264604811, 'mean_word_length': 3.8744769874476988, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '613142', 'license': 'MIT', 'n_tokens_mistral': 387, 'n_tokens_neox': 382, 'n_words': 92, 'path': '.ipynb_checkpoints/15. Context Managers and else Blocks-checkpoint.ipynb', 'repo_name': 'stephenl6705/fluentPy', 'size': '1164'}