Kind of blocks in Python

In Ruby I can say:

def get_connection
  db = connect_to_db()
  yield
  db.close()
end

and then call it

get_connection do
  # action1.....
  # action2.....
  # action3.....
end

In Python I have to say

def get_connection(code_block):
  db = connect_to_db()
  code_block()
  db.close()

get_connection(method1)

def method1():
   # action1.....
   # action2.....
   # action3.....

It's not convenient since I have to create an extra method1. Notice that method1 can be big. Is there any way to emulate Ruby's anonymous blocks in Python?

Answers


Yes. Use the 'with' statement:

Using classes

class get_connection(object):
    def __enter__(self):
        self.connect_to_db()
    def __exit__(self, *args, **kwargs):
        self.close()
    def some_db_method(self,...):
        ...

And use it like this:

with get_connection() as db:
    db.some_db_method(...)

This does the following:

 self.connect_to_db()
 db.some_db_method(...)
 self.close()

Have a look here: http://docs.python.org/release/2.5/whatsnew/pep-343.html . You can use the arguments taken by __exit__ to handle exceptions within the with statement, etc.

Using functions

from contextlib import contextmanager

@contextmanager
def db_connection():
    db = connect_to_db()
    yield db
    db.close()

and use this:

with db_connection() as db:
    db.some_db_method()

(Perhaps this is closer to your ruby equivalent. Also, see here for more details: http://preshing.com/20110920/the-python-with-statement-by-example)

Hope this helps


Need Your Help

Difference between rendered and visible attributes of <p:dialog>

jsf primefaces

I am using PrimeFaces 3.2 in my project. I wanted to know what is the difference between setting the rendered attribute of a &lt;p:dialog&gt; as against setting the visible attribute. When should I...

django registration not loading the registration_complete.html template

django django-registration

I am using Django 1.3 and django-registration 0.8. I am trying to use the RegistrationFormUniqueEmail class to enforce unique emails.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.