[Python-ideas] with expression

Ed Kellett edk141 at gmail.com
Sun Feb 23 12:13:45 CET 2014


On 20 February 2014 18:50, Yann Kaiser <kaiser.yann at gmail.com> wrote:
> ...

some uses I've thought of:

# current:

try:
    with open('foo.txt', 'r') as f:
        thing = f.read()
except IOError:
    thing = 'default'

# except-expression:

with open('foo.txt', 'r') as f:
    thing = f.read() except IOError: 'default'

# with-expression:

thing = f.read() with open('foo.txt', 'r') as f, default('default', IOError)

#########

# current:

try:
    thing = operation_may_fail()
except:
    thing = 42

# except-expression:

thing = operation_may_fail() except Exception: 42

# with-expression:

thing = operation_may_fail() with computed_default(lambda: 42)

#########

# current:

# assuming one of these functions takes a very long time, and the other
# blocks a thread you don't want to be blocking for long
with some_lock:
    x = do_unsafe_thing()
with another_lock:
    y = other_thing()
frobnicate(x, y)

# except-expression:
# (no change)

# with-expression:

frobnicate((do_unsafe_thing() with some_lock),
           (other_thing() with another_lock))

#########

# current:

try:
    os.unlink('/sbin/init')
except OSError:
    pass
# -- or --
with suppress(OSError):
    os.unlink('/sbin/init')

# except-expression:

os.unlink('/sbin/init') except OSError: None
# (PEP 463 says you should use a with statement)

# with-expression:

os.unlink('/sbin/init') with suppress(OSError)


More information about the Python-ideas mailing list