Dateideskriptor in einer Funktionskörper schließen oder nicht?Python

Python-Programme
Anonymous
 Dateideskriptor in einer Funktionskörper schließen oder nicht?

Post by Anonymous »

Ich habe viele Male ein oftes Code wie diesen < /p>
gefunden

Code: Select all

def content(path):
return open(path).read()
< /code>
Ich habe ein solches Konstrukt getroffen, typischerweise von Programmierern, die aus Sprachen auf niedrigerer Ebene wie C oder C ++ stammen.def content(path):
with open(path) as fd:
return fd.read()
< /code>
und die "sicherere" Version < /p>
def content(path):
with open(path) as fd:
text = fd.read()
return text
< /code>

Der 1-Liner ist sehr attraktiv und kann häufig als Rückrufimplementierung verwendet werden (z. B. in der GUI-Umgebung), aber ich weiß nicht, ob es in der Produktion sicher ist oder ob es als Pythonic als Pythonic in Betracht gezogen wird. Pil.image 

Öffnen/Schließen Sie Version:

Code: Select all

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
< /code>
Öffnen + GC -Version: (weniger ausführlich) < /p>
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()

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post