ANN: experimental patch to allow importing from file-like objects

Gerson Kurz gerson.kurz at t-online.de
Sat Mar 2 14:25:17 EST 2002


On 02 Mar 2002 12:30:42 GMT, Gordon McMillan <gmcm at hypernet.com>
wrote:

>Most people doing something like this don't use imp.load_module.
>
>First you need a code object for the module. If it's source:
>
>  co = compile(open(srcfile, 'r').read()+'\n', srcfile, 'exec')
>
>If it's already compiled (and still fresh etc.)
>
>  stuff = open(bytecodefile, 'rb').read()
>  co = marshal.loads(stuff[8:])
>
>Then you need a module object
>
>  mod = imp.new_module(nm)
>
>(You need to set up mod.__file__, mod.__name__ etc. here).
>And finally
>
>  sys.modules[fqname] = mod
>  exec co in mod.__dict__
>

Hey, thats' cool! I didn't know that. 

I must say, though, that the documentation on this in the Python
reference manual is *quite* rudimentary. Well, at the very least I
learned something about python internals and PyTokenizer ;)

But I still feel that the python core should be more "pythonesque".

There are a gazillion (ok, more like 40) places in ./Include, that use
a "FILE *" as argument. As this is the external interface of python, I
think it would be better if it expected PyFile-like objects instead.
For example, look at marshal.dump(). You cannot pass a file-like
object if you wanted to (because, alas, the implementation expects
FILE*). You have to use dumps() and write that. 

Is this just a decision dictated by "the need for speed", or is there
any motivation behind it? 

On a related note, (I've asked this before to no avail) - how do I
successfully subclass files & open them? 

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