[Biopython-dev] [Bug 2752] Context management for Bio.Entrez handles

bugzilla-daemon at portal.open-bio.org bugzilla-daemon at portal.open-bio.org
Tue Feb 10 05:12:12 EST 2009


http://bugzilla.open-bio.org/show_bug.cgi?id=2752





------- Comment #3 from biopython-bugzilla at maubp.freeserve.co.uk  2009-02-10 05:12 EST -------
(In reply to comment #0)
> To make Bio.Entrez work this way, we could just add @contextmanager decorators
> to efetch() and the others, ...

Isn't it simpler just to change our Bio.Entrez._open function instead of all
the Bio.Entrez.e* functions?

These Bio.Entrez functions are just wrappers for urllib (via our _open
function). From reading the example at the end of this page, it looks like
closing a urllib handle is left to the user:
http://www.python.org/doc/2.5.1/whatsnew/pep-343.html

e.g.
import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)

In the short term (without altering Biopython) using this should work,
shouldn't it?

from contextlib import closing
from Bio import Entrez
def write_gbk(gi):
    with open("gi%s.gbk" % gi, 'w+') as outfile:
        with closing(Entrez.efetch(db='protein',
                                   rettype='genbank',
                                   id=gi)) as gbk:
            text = gbk.read()
        outfile.write(text)
    print "Wrote", gi


Furthermore, rather than messing about with a factory class (which sounds
overly complicated), can we just use contextlib.closing ourselves in the
Bio.Entrez._open function?  This approach should also be easy to keep backwards
compatibility with older versions of python.

i.e. At the end of _open, replace:

return uhandle

with:

try :
   from contextlib import closing
   return closing(uhandle)
except ImportError :
   return uhandle

(I haven't tested this yet)

Alternatively, we could add the __enter__ and __exit__ methods to the
Bio.File.UndoHandle object instead (which would benefit any code using them,
not just Bio.Entrez).


-- 
Configure bugmail: http://bugzilla.open-bio.org/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
You are the assignee for the bug, or are watching the assignee.


More information about the Biopython-dev mailing list