This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Necessary to close pysam.AlignmentFile?

Hi, This question is for those who are familiar with pysam.

pysam is used as follows:

samfile = pysam.AlignmentFile('file.bam', 'rb')

In the examples shown in the documentation, he always ends the code with:

samfile.close()

Similar to when closing a file in python.

I can't find anything about the exact purpose of this in the documentation for pysam. Is it similar to when closing a regular file?

I'm asking because I wan't to create a function where samfile is returned to the caller function. Would I then need to close the samfile in the caller function?

eg.:

def open_bam(file):
    samfile = pysam.AlignmentFile(file, 'rb')
    return samfile
    samfile.close()

And then use it as follows:

def analyze_bam(sfile):
    for read in sfile.fetch():
        print read

    sfile.close()

Or can I simply skip closing it in analyze_bam()?

python pysam bam

1 answer

If you open a file in a function and want to return it, then you can't close it. In your open_bam() example, remove the last line, which will never be reached.

Anyway, yes, closing samfile is the same as closing a regular file. In theory python will do it for you when the process finishes, but I've seen cases where this doesn't happen (mostly with images in matplotlib).

Okay, so if I remove samfile.close() from open_bam() and keep return samfile, could I then do something like this?:

bam_graph(open_bam('filename.bam'))

def bam_graph(samfile):
    Code to produce graph and then end it with:
    samfile.close()

Will it be okay then to structure my script like this or is it possible that this will invoke problems further down the road?

Log in to answer this question.