Context Manager – with code-block

In modernen Python Programmen wird häufig ein with code-Block verwendet um Resourcen zu managen, z.B.


with open("out.txt", "w") as myf:
    myf.write("Hello, World!")


Wozu ist das gut?

Naives Beispiel:


myf = open("out.txt", "w")
myf.write("Hello, World!")
myf.close()

Bei Problemen in write Funktion tritt exception auf: \bgroup\color{dgreen}\ensuremath{\color{dgreen}{\Rightarrow}}\egroup close Funktion wird nicht gerufen. Folge: Bei wiederholtem Auftreten wird jeweils File-Descriptor angelegt, aber nicht ordentlich beendet.

Besser mit Exceptions:


# Safely open the myf
myf = open("out.txt", "w")

try:
    myf.write("Hello, World!")
except Exception as e:
    print(f"An error occurred while writing to the myf: {e}")
finally:
    # Make sure to close the myf after using it
    myf.close()

Finally Keyword bewirkt dass close Funktion auf jeden Fall gerufen wird, egal ob Exception auftritt oder nicht.

Etwas umständlich, obige Version mit with im wesentlichen äquivalent, aber deutlich kompakter.

Weitere Details z.B. in Real Python: with-statement