[Python] close or not close file descriptor in a function body?

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    I found many many times a code like this

    def content(path):
    return open(path).read()


    I have met such construct typically by programmers coming from lower level languages such as C or C++.

    More conventional constructs are instead the following:

    def content(path):
    with open(path) as fd:
    return fd.read()


    and the most "safer" version

    def content(path):
    with open(path) as fd:
    text = fd.read()
    return text


    The 1-liner is quite attractive and could be used often as a callback implementation (for example in in GUI environment) but I don't know if it is safe to use in production or if it is consider Pythonic.


    EDIT: another example using the descriptor io.BytesIO and PIL.Image

    Open/close version:

    def array2bytes_image(a:np.array, out_format:str='PNG') -> bytes:
    """Numpy array - 1:1 -> image as bytes"""
    im = Image.fromarray(a, mode='L') # 8-pixel grayscale
    bio_im = io.BytesIO()
    im.save(bio_im, format=out_format.upper())
    im_binary = bio_im.getvalue()
    bio_im.close()
    im.close()
    return im_binary


    Open + GC version: (less verbose)

    def array2bytes_image(a:np.array, out_format:str='PNG') -> bytes:
    """Numpy array - 1:1 -> image as bytes"""
    im = Image.fromarray(a, mode='L') # 8-pixel grayscale
    bio_im = io.BytesIO()
    im.save(bio_im, format=out_format.upper())
    return bio_im.getvalue()

    Continue reading...

Compartilhe esta Página