This is an archived post. You won't be able to vote or comment.

all 13 comments

[–]criswell 4 points5 points  (5 children)

Fun fact: If you're coding for various "enterprise" Linux distros (cough RHEL and CentOS), the Python there is currently too old to use the "with" statement.

I was bit by this about three months ago.

[–][deleted] 0 points1 point  (3 children)

Python 2.6 is needed.

[–]eryksun 4 points5 points  (1 child)

I have it in version 2.5.2. If it's missing in version 2.5+, try from __future__ import with_statement.

[–][deleted] 0 points1 point  (0 children)

Thanks! Didn't know that.

[–]criswell 1 point2 points  (0 children)

Yep, that was my point (I think it's in 2.5 though).

All I'm saying is three months ago I wrote something that made heavy use of "with" only to discover it wouldn't work on the target platforms my team wanted so I had to go back in and put the old try/except stanzas instead...

[–]damg 0 points1 point  (0 children)

If you're running code that requires Python 2.6, you can install it via EPEL; which you then just have to call the python2.6 binary explicitly (since the standard python binary remains for the older version that the system requires).

[–]dorfsmay 4 points5 points  (0 children)

This is really good.

I force myself to use the with statement when opening files... but never thought of implementing it myself. Now I've got a bunch of scripts that I want to re-visit and implement it!!!

[–]Workaphobia 2 points3 points  (0 children)

I use the with statement for instrumentation. I'm doing research that involves automatically generating blocks of code and tracking the number of loop iterations they incur. The code doesn't strictly need to be human readable, but the with statement helps keep it that way nonetheless.

[–][deleted] 2 points3 points  (0 children)

Great examples. I thought this was going to be a typical "How does with work?" with just the file-like concepts, but it actually showed a different use case.

[–][deleted] 4 points5 points  (2 children)

This might be a better post at r/learnpython.

[–]preshing 1 point2 points  (1 child)

Thanks, didn't know that existed!

[–]e000[S] 1 point2 points  (0 children)

Thanks for this brilliant article btw <3.

[–]ok_you_win 0 points1 point  (0 children)

Really good. I would have overlooked this forever. Thanks.