[Biopython-dev] [Bug 3105] Bio.Nexus useless line

bugzilla-daemon at portal.open-bio.org bugzilla-daemon at portal.open-bio.org
Sun Jul 4 20:22:28 UTC 2010


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





------- Comment #3 from eric.talevich at gmail.com  2010-07-04 16:22 EST -------
(In reply to comment #2)
> Given other
> bits of Biopython now do the same, we could perhaps have a single bit
> of shared code for this - or at least consistent coding style.
> 

Here's a snippet I use for myself:

import contextlib

@contextlib.contextmanager
def maybe_open(infile, mode='r'):
    """Take a file name or a handle, and return a handle.

    Simplifies creating functions that automagically accept either a file name
    or an already opened file handle.
    """
    do_close = False
    if isinstance(infile, basestring):
        do_close = True
        handle = open(infile, mode)
    else:
        handle = infile
    yield handle
    if do_close:
        handle.close()


Use like:
>>> with maybe_open(filename_or_handle) as handle: ...


For Py2.4 compliance, you can just drop the @contextlib.contextmanager
decorator and leave the function as it is. Then this works:

>>> for handle in maybe_open(fname): ...

It's an iterator of one item, taking care of loose ends when it terminates.
Neat, huh?

I suspect that yielding from a try/finally block, which is forbidden in Py2.4,
is related to the with statement under the hood in Py2.5+. Since maybe_open
kind of needs that protection to work safely, I think the copy/paste approach
is fine until we officially drop Py2.4 support.


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