Help! File objects and scoping

Dave Benjamin ramen at lackingtalent.com
Tue Jun 7 20:49:15 EDT 2005


bens wrote:
> I'm trying to return an 'mmap' object from a function.  The return
> works, but some of the object's methods crash.  Here are two examples
> 
> doesntwork.py
> ---------------------------
> import mmap
> import os
> 
> name="/any/real/file/on/my/hard/drive"
> 
> def getfile(name):
>     somefile=file(name, 'r+b')
>     mmapped = mmap.mmap(fileno=somefile.fileno(), \
> length=os.path.getsize(name))
>     return mmapped

Here's the problem: the "mmap" object doesn't have a reference to 
"somefile", only to its file descriptor number. So, when getfile() goes 
out of scope, there are no references left, and the file gets closed 
automatically.

One way to avoid this problem is to return the file object as well as 
the "mmap" object, ie.:

def getfile(name):
     somefile = file(name, 'r+b')
     mmapped = mmap.mmap(fileno=somefile.fileno(),
                         length=os.path.getsize(name))
     return (somefile, mmapped)

(somefile, mmapped) = getfile(name)

# do something with mmapped...

Now, as long as you keep "somefile" in scope, the file won't get closed. 
You could also build an object and make both "somefile" and "mmapped" 
attributes of this object.

Caveat: There may be a better way of doing this. I've never used "mmap".

Dave



More information about the Python-list mailing list