# Context managers (with)
#
# Le bloc with garantit __exit__ en sortie, même en cas d'exception.
import('io')
import('contextlib')
print("⇒ Lecture de fichier")
with f = io.open('/dev/null') {
print("fichier ouvert:", f)
data = f.read()
print("lu:", len(data), "octets")
}
# f.__exit__() appelé automatiquement ici
print()
print("⇒ Suppression d'exception")
with _ = contextlib.suppress(ValueError) {
raise ValueError("cette erreur est ignorée")
}
print("après suppress: pas d'erreur")
print()
print("⇒ Exception non supprimée")
try {
with f = io.open('/dev/null') {
raise TypeError("pas supprimée")
}
} except {
e: TypeError => { print("attrapée:", e) }
}