[Python-Dev] how important is setting co_filename for a module being imported to what __file__ is set to?

P.J. Eby pje at telecommunity.com
Mon Aug 31 21:08:51 CEST 2009


At 09:33 AM 8/31/2009 -0700, Guido van Rossum wrote:
>Of course, tracking down all the code objects in the return value of
>marshal.load*() might be a bit tricky -- API-wise I still think that
>making it an argument to marshal.load*() might be simpler. Also it
>would preserve the purity of code objects.

Or maybe we could just do something like this:

     from new import code

     def with_changed_filename(code_ob, filename):
         def remap(ob):
             if not isinstance(ob, code):
                 return ob
             return code(
                 ob.co_argcount, ob.co_nlocals, ob.co_stacksize, 
ob.co_flags, ob.co_code,
                 map(remap, ob.co_consts), ob.co_names, 
ob.co_varnames, filename,
                 ob.co_name, ob.co_firstlineno, ob.co_lnotab, ob.co_freevars,
                 ob.co_cellvars
             )
         return remap(code_ob)

Granted, this takes a bit more memory than an in-place modification, 
but it's immediately usable and at least works wherever new.code is available.

(I've not tested the above, so it may not work.  I seem to recall the 
last time I wrote something like this there was something tricky 
about handling co_freevars and co_cellvars; I think you may need to 
omit them if empty, or convert them to None, or from None to an empty 
tuple or some such rigamarole.   And a 3.x version is left as an 
exercise for the reader.  ;-) )



More information about the Python-Dev mailing list