Import-Hook and subclassed file objects

Gerson Kurz gerson.kurz at t-online.de
Fri Mar 1 06:28:42 EST 2002


I want to create an import hook that reads data from encrypted files.
To redirect the import hook, I do this:

----------- (snip here) -------------

# redirect import hook
old_import_func = __import__

def my_import_func(name, globals=None, locals=None, fromlist=None):
    global old_import_func
    
    if name[:10] == "encrypted.":

        # todo: load encrypted module
        return imp.load_module(name, file, '',
('.dat','rb',imp.PY_SOURCE)) 

    # use original code    
    return old_import_func( name, globals, locals, fromlist )

__builtins__.__import__ = my_import_func

import encrypted.test

----------- (snip here) -------------

(Of course, I'll use lambda for that in the final version ;)

Anyway, I have two problems with that. imp.load_module expects a file
object. But, Problem #1, the file object cannot be a subclassed
"file-type" class. If I define my own file class, I get an error
bad/closed file object. Looking at the PythonCore source, I find that
the C runtime uses the raw FILE* and not abstract PyFile functions.
See function "imp_load_module" in "Python\Import.c": converts
Py-File-Object to raw FILE* and then uses that further on. 

I think I'll have a more deeper look at the python sources and see if
I can add PyFileObject-style access. 

Problem #2, how do I subclass files? I try this:

----------- (snip here) -------------

class my_file_class(file):

    def read(self,size):
        # todo: add read implementation

----------- (snip here) -------------

the problem is - where to I subclass a file returned from open()?
open() always returns the builtin file class. Attempting to do this

----------- (snip here) -------------

raw_file = open(...)
my_file = my_file_class()
raw_file.read = my_file.read

----------- (snip here) -------------

I'll get an error that read is a read-only method.








More information about the Python-list mailing list