Re: marshal and code objects

lance@fox.com
Wed, 6 Apr 94 9:48:36 PDT

> Date: Tue, 05 Apr 94 21:54:11 -0400
> From: Tim Peters <tim@ksr.com>
>
> > [richard]
> > Is there anyway to assign a code object to a function or method in
> > python?
> >
> > If not why are code objects supported as a valid type that can be
> > packed up using the marshal module in python?
>
> I suspect the accurate answer is "just because that's the way Python
> itself writes out .pyc files" -- i.e., a .pyc file consists of a header
> and a marshaled code object. So it's extremely useful as-is -- just not
> to us users directly!

Actually .pyc files are not the only things that save marshalled code
objects. I have a screen generation class that loads a screen definition
file that contains the screen and python code to run for that screen.
I then use compile() to compile the python code and then saves the compiled
code to execute at a later time. I then save the code objects to files
to load faster similar to what is done with .pyc files except I look
at the compile time each time a screen is loaded and will recompile and
use the new version anytime the file is changed.. evan during a single run.

Actually I do the following:

# ok.. lets compile the code first.. then parse the screen
# to make sure we can look up everything needed!
t= '<screen \'' + screen_name + '\'>'
try:
screen_code = compile(screen_code_text,t,'exec')
except:
self.__class__.error = (sys.exc_type,sys.exc_value,
t,sys.failed_lineno)
# sys.failed_lineno is a hack I put in.. This needs
# to be changed to Guido's "NEW" way of reporting
# the line number.
return 0
l_ns = {}
exec screen_code in l_ns

And then to execute anything in the compiled code, I then call the function
as:
rtn_val = l_ns['function_name'](args)

--
Lance Ellinghouse                lance@fox.com