Calling local functions from the C API

Alex Martelli aleax at aleax.it
Mon Nov 18 05:03:30 EST 2002


Jon Parise wrote:
   ...
>> In Python, you could write
>> 
>> d = {}
>> exec sourcecode in d
>> func = d['SomeFunction']
>> func()
>> 
>> Now just do the same in C. Which of the four steps is unclear to you?
>  
> Thinks makes sense, I think (although I may have more questions when I
> work on my actual implementation).
> 
> The one thing I note, however, is that I just can't execute arbitrary
> blocks of code via PyRun_SimpleString() and expect to be able to
> execute a function defined in one of those blocks of code again.
> Instead, it looks like I'll need to use Py_CompileString() or similar
> to maintain a code object.
> 
> Is that correct?

Not really.  When an arbitrary block of source code contains a
def statement, you want to EXECUTE that block of code, specifically
to execute that def statement, which creates the function object
that you can later call (not sure what you mean by "again" here).
If you just COMPILE the block to bytecode, the function object
will not be created until the def statement is executed.

Maybe the key tidbit you need to keep in mind is: def is a statement
just like any other -- when the def statement EXECUTES, it creates
a function object and binds that object to a name.  So, def is quite
similar to an assignment statement "name = expr", where the expr
part creates an object and the assignment binds that object to the
name.  Sometimes programmers with experience in other languages
have a hard time grasping the simple fact that def is a statement,
and the consequences thereof, because they may be thinking in terms
of "declarations" (which other languages have but Python doesn't).


Alex




More information about the Python-list mailing list