with statement and standard library

Chris Rebert clp2 at rebertia.com
Mon Feb 22 00:18:19 CET 2010

On Sun, Feb 21, 2010 at 3:21 PM, John Nagle <nagle at animats.com> wrote:
> nobrowser wrote:
>> Hi.  The with statement is certainly nifty.  The trouble is, the
>> *only* two documented examples how it can be used with the library
>> classes are file objects (which I use all the time) and thread locks
>> which I almost never use.  Yet there are many, many classes in the
>> library whose use would be more elegant and readable if the with
>> statement could be employed.  Start with the connection objects in
>> httplib and you can probably come up with 10 others easily.
>   "with" is important for locks because it matters when they're
> released.  It's not as important if release is just resource
> recovery.  Reference counting will recover most objects when they
> go out of scope anyway.

If you're using CPython that is. The other implementations don't use
refcounting and thus don't guarantee the GC will be that timely.
So if one wants maximum portability, the `with` statement is *quite* useful.

Not to mention there are other uses for `with` besides just freeing
resources; e.g. setting a temporary decimal arithmetic context.


More information about the Python-list mailing list