python contextmanagers and ruby blocks

Francesco Bochicchio bockman at virgilio.it
Sat Feb 21 06:00:56 EST 2009


On Sat, 21 Feb 2009 00:46:08 -0800, Alia Khouri wrote:

> As an exercise, I recently translated one of my python scripts (http://
> code.activestate.com/recipes/576643/) to haskell (a penultimate
> version exists at http://groups.google.com/group/comp.lang.haskell/browse_thread/thread/fb1ebd986b44244e#
> in case anyone is interested) with the result that haskell has now
> become my second favourite language (after python of course :-)
> 
> Just to change mental gears a bit, I'd now like to do the same and
> create a ruby version. As I've progressed on the latter, I've been
> struck by how pervasive the use of blocks is in ruby. For example:
>

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

 
> 
> Now, python's relatively new contextmanagers seem to provide something
> similar such that one can write:
> 

... 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.


> 
> Which brings me to my questions:
> 
> 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.

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'. And -
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.

Ciao
----
FB  


 


Ruby blocks - for the little I know of ruby - are anonymous block of
codes


> 2. If there is a gap in power or expressiveness in python's context
> managers relative to ruby's blocks, what are possible (syntactic and
> non-syntactic) proposals to bridge this gap?
> 
> Thank you for your responses.
> 
> AK




More information about the Python-list mailing list