[Python] Context Managers as a class vs. function?

Discussão em 'Python' iniciado por Stack, Setembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I have been looking into Python's contextmanager (more specifically, Python 3's contextlib or its back ported contextlib2) as of late, and I was wondering what were the advantages/disadvantages writing them as a class vs. a function?

    They both seem to function the same way and handle exceptions the same way. There's a lot of cool utilities like ExitStack(), but those utilities seem to be implementable in context managers written as classes or functions. Thus, I'm struggling to find a good reason as to why one would want to write context managers verbosely as a class when they can be written as a function and just slap on the contextmanager decorator.

    Here's a trivial example I wrote to showcase both doing the same thing:

    # !/usr/bin/python -u
    # encoding: utf-8

    from contextlib import contextmanager

    # Function-based
    @contextmanager
    def func_custom_open(filename, mode):
    try:
    f = open(filename, mode)
    yield f
    except Exception as e:
    print(e)
    finally:
    f.close()

    # Class-based
    class class_custom_open(object):

    def __init__(self, filename, mode):
    self.f = open(filename, mode)

    def __enter__(self):
    return self.f

    def __exit__(self, type, value, traceback):
    self.f.close()


    if __name__ == '__main__':

    # Function-based
    with func_custom_open('holafile_func.txt', 'w') as func_f:
    func_f.write('hola func!')

    # Class-based
    with class_custom_open('holafile_class.txt', 'w') as class_f:
    class_f.write('hola class!')

    Continue reading...

Compartilhe esta Página