← Back to team overview

launchpad-dev team mailing list archive

Re: The with statement

 

On Feb 10, 2010, at 05:28 PM, Bjorn Tillenius wrote:

> think we should be a bit careful using it for other things than files.
>I'm sure there are good use cases for using with with custom
>implementations, but we should be careful not to over-use it. Just
>because it's easy to write, doesn't mean that we should do it. It's very
>easy to get carried away, wanting to use new features just because. It's
>important to think about the end result.

I completely agree that we should be careful, and tasteful, but of course
that's true of any wacky Python feature, not just with-statements. :)

I sort of envision that we'll find some common patterns in our code that fit
well as context managers.  I'm hoping that we can write a few generic classes,
and that we'll get used to seeing them in our code.  Things like temporarily
changing the umask or cwd come to mind.  Like a lot of these, it'll take some
time to propagate across our collective consciousness, so when the dev and
reviewer agree that a useful context manager has been written, documenting it
in the wiki and/or mailing list would be helpful.

>So, when writing context manager implementations, you (and the reviewer)
>should ask youself the question: how easy is it to see what's going on
>when the with statement is used? The with statement does add a level of
>magic. If you need to chase down the implementation to figure out what's
>going on, it's not a good design. As I see it, the with statement is
>mainly useful wehre you have a well-known behaviour, where it's easy to
>find out what's going on (for example from the name), or when the
>clean-up step isn't important. This doesn't mean that we should avoid
>writing our own context managers at all cost, just that we should
>evaluate the benefit. The more an object is used in the code, the more
>likely it is that the behaviour will be well-known.

Right.  Above all, if you do decide to write a context manager, making it read
well in English when used as the target of the 'with' is half the battle.

    with cwd('/path/to/stuff'):
        # ...

is pretty obvious.

-Barry

Attachment: signature.asc
Description: PGP signature


Follow ups

References