python contextmanagers and ruby blocks

Alia K alia_khouri at yahoo.com
Sat Feb 21 08:20:51 EST 2009


Francesco wrote:

> ... ruby code that shows the most twisted 'Hellow world' example I have
> ever seen :-) ...

and I was gunning for the simplest possible example (-:


> ... python code doing the same thing - apparently -
> of prevous ruby code, using context managers in a way that I believe the
> authors of contextlib module never thought of.

Methinks they probably thought of such usage.

> > 1. To what extent are python's contextmanagers similar or equivalent
> > to ruby's blocks?

> ASAIK, context managers are nothing like ruby blocks.
> Context managers have a very specific purpose : to make people able to
> abstract the code that one writes to 'enter a context'
> (i.e. open a file, start a transaction, ... ) and 'leave a context'
> (i.e. close a file, commit or rollback the transaction ... ).
> So that you can separate context handling code from the code that performs
> actions insed that context, factoring out the first for reuse and better
> code maintenance.

Thinking about it: I suppose one could say in python a contextmanager
defines the functional context of a block of code and makes it a first
class construct in the language, whereas in ruby the block itself is a
first class citizen -- contextmanagers are like the inverse of blocks.

> Ruby blocks are blocks of code which can be passed as
> objects for a number of different usage - for instance to make context
> management stuff. If I have to compare them to something in Python, I
> would say they are 'lambda on steroids' or 'nameless functions'.

Agreed, but also they are more tightly integrated e.g. the &block
construct which can be passed into functions...

> personally - I don't like them just as I don't like lambdas in python for
> anything but one-liners and I don't like anonymous functions in haskell
> (which I am painfully trying to learn ). They may be cool to write, but
> they look not very readable to me - but maybe this is just me.

In case you are learning haskell, here are some excellent guides
(order is important) :

* Learn you a haskell: http://learnyouahaskell.com/chapters
* Real World Haskell: http://book.realworldhaskell.org/
* Typeclassopedia: http://byorgey.wordpress.com/2009/02/16/the-typeclassopedia-request-for-feedback/

(I'm personally still scratching the surface of it all...)

back to the subject...

I suppose because contextmanagers (indeed decorators) are so
relatively new to python, it will probably take a little while for
these constructs to comprehensively penetrate the stdlib. It's already
happened with files, locks, and db transactions but I'm sure there are
many instances where one could benefit from using the with statement.

Nevertheless, I remain curious about whether once can use the
contextmanager in python to achieve the full power of ruby's blocks...

Best,

AK




More information about the Python-list mailing list