Letting a program get a StringIO instance by file('test.txt') virtual file redirection

Bengt Richter bokr at oz.net
Thu Jul 25 02:45:11 EDT 2002


Sometimes I like to make a quick example to post without actually
creating files (except maybe one for the example source). This is
hard if the example involves opening a file as in f=file('test.txt','rb').

If file and open would look first in a (proposed new) directory (like sys.modules),
but perhaps named sys.vfiles, and do different things according to the value found
using the file path as a key (if found there) instead of always opening a disk file,
then one could write

    import sys, StringIO
    sys.vfiles['test.txt'] = StringIO.StringAsFile("""\
def foo(): print 'Hello'
"""
    execfile('test.txt')
    foo()

and expect to get a Hello.

This assumes a new class in StringIO to create an object containing a string
which would have an open method to return a new StringIO instance containing
the string. That's so it could be opened multiple times to get independent
StringIO "files". It would be recognized by file/open when it looked in sys.vfiles.

Also, file/open could recognize plain string values as redirections, like
a symbolic link. You could even have it recognize some URI strings and do
the appropriate open, e.g.,

    sys.vfiles['python_site'] = 'http://www.python.org/'
    top_page = file('python_site').read()

It could also be a way make file/whatever names platform independent.
site.py could do whatever standard setup was decided upon.

Just some thoughts, after cluttering my pywk/junk directory, and then thinking
there might might be a useful idea in there somewhere ;-)

Something similar came up before, and apparently lisp has ways to do similar things,
but the idea died. I just thought the sys.vfiles incarnation might be clearer.

Regards,
Bengt Richter



More information about the Python-list mailing list