Tutorial
with

Die with-Anweisung (siehe PEP-0343) ist ein neues Schlüsselwort, mit dem man einige Dinge deutlich verkürzen kann. Am besten sieht man es bei ein paar Beispielen.

mit Python v2.5

with wurde mit Python 2.5 eingeführt, muss aber explizit aktiviert werden, weil es ein Schlüsselwort ist. Somit ist die Einführung nicht 100% rückwärtskompatibel, z.B. könnten vorhandene Variablen/Funktionsnamen 'überschrieben' werden.

Die Aktivierung erfolgt über die sog. Future-Anweisung:

   1 from __future__ import with_statement

Ab Python 2.6 entfällt diese Notwendigkeit. with ist dann fester Bestandteil der Sprache.

Beispiele

Datei öffnen

ohne with

   1 f = open('FooBar.txt', 'r')
   2 try:
   3     for line in f:
   4         print line
   5 finally:
   6     f.close()

mit with

   1 with open('FooBar.txt', 'r') as f:
   2     for line in f:
   3         print line

threading lock

ohne with

   1 >>> import threading
   2 >>> my_lock = threading.Lock()
   3 >>> def my_global_function():
   4 ...     my_lock.acquire()
   5 ...     try:
   6 ...         print "Schritt 1"
   7 ...         print "Schritt 2"
   8 ...     finally:
   9 ...         my_lock.release()

mit with

   1 >>> import threading
   2 >>> my_lock = threading.Lock()
   3 >>> def my_global_function():
   4 ...     with my_lock:
   5 ...         print "Schritt 1"
   6 ...         print "Schritt 2"

Tutorial/with (last edited 2009-06-17 16:14:15 by localhost)